In comp.lang.javascript message <Xn********************@194.109.133.242>
, Mon, 18 Feb 2008 08:01:18, Evertjan. <ex**************@interxnl.net>
posted:
>
I already gave this regex in another branch of this tread:
function replaceOneChar(s,c,n){
var re = new RegExp('^(.{'+ --n +'}).(.*)$','');
return s.replace(re,'$1'+c+'$2');
};
A non regex solution would be:
function replaceOneChar(s,c,n){
(s = s.split(''))[--n] = c;
return s.join('');
};
There is an overhead to the construction of a RegExp and to the
commencement of each use, but after that the scanning and replacement
will be reasonably fast.
Method split requires the creation of a number of Objects for short-term
use, but after that the replacement will be quick.
With XP sp2 IE6, I find that the two methods are of similar speed for
8-character strings; for a 2-character string, RegExp takes about half
as long again as split; for a 30-character string, split takes about
twice as long as RegExp; for a 90-character string, split takes over
five times as long as RegExp.
--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE6 IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.