views:

644

answers:

5

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.

A: 

Use the replace() method of the String object.

Franci Penov
A: 
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");

newString now is 'Thas as a strang'

Sani Huttunen
You'll only get `Thas is a string`, not `Thas as a strang`.
KennyTM
You are correct. Changed.
Sani Huttunen
A: 

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. ;)

Crozin
Using a string in `replace` does only replace the first occurrence and not all.
Gumbo
@Gumbo: I know. That's why I also wrote an example with regexp. ;)
Crozin
+4  A: 

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");
Gumbo
Thank you very much, I did not know of the 'g' flag you can use.
Anriëtte Combrink
A: 

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.

Andy E