Hi there
What is the fastest way to replace all instances of a string/character in a string in Javascript? A while
, a for
-loop, a regular expression?
Thanks in advance.
Hi there
What is the fastest way to replace all instances of a string/character in a string in Javascript? A while
, a for
-loop, a regular expression?
Thanks in advance.
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");
newString now is 'Thas as a strang'
What's the fastest I don't know, but I know what's the most readable - that what's shortest and simplest. Even if it's a little bit slower than other solution it's worth to use.
So use:
"string".replace("a", "b");
"string".replace(/abc?/g, "def");
And enjoy good code instead of faster (well... 1/100000 sec. is not a difference) and ugly one. ;)
The easiest would be to use a regular expression with g flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
re = new RegExp(pattern, "g");
I regular expression would most certainly be faster on large strings. With small strings, on the other hand, a loop could possibly beat a regular expression but it would probably be a micro-optimisation.
It's particularly difficult to replace multiple characters using a for-loop, because then you get into substring
territory which would bring the efficiency down a bit.
I would suggest sticking with a regular expression because, as Gumbo and others mentioned, it's at least easier.
A decent example of non-regex I can think of would be the following (untested):
function findAndReplace(haystack, needle, replace)
{
var cindex = 0;
var rtnStr = "";
while (cIndex = haystack.indexOf(needle) >= 0)
{
rtnStr += haystack.substring(0, cIndex) + replace;
haystack = haystack.substring(cIndex+needle.length);
}
return rtnStr;
}
This way you're not looping over individual characters. I'm unsure as to how big the string would have to be before a regex became more efficient though.