replace all in JavaScript

Maybe you already had the problem that you needed to use a a simple replace in JavaScript. The problem is while using "string.replace('old string', 'new string')" just the first match will be replaced. This is kind of weird if you are coming from the .Net world.
So there are two ways to perform a replace all in JavaScript: the replacing with arrays and the regex replacing


Lets take a look at the array replacing:

1
2
3
function replaceAll(string, find, replace) {
 return string.split(find).join(replace);
}

In this function you are replacing the string find with replace. This works the way that the var string will be splitted at first by find. A split in JavaScript means that the string you are looking for will be removed and used as seperator for the array. The join command merges array values to a string and adds a seperator.

The second way is the regex operation:

1
2
3
function replaceAll(string, find, replace) {
  return string.replace(new RegExp(find, 'g'), replace);
}

In this method you are using the replace function again, but this time with the help of a regex that is returning all places where your searchstring exists.

Comments

Popular posts from this blog

How to support multiple languages in WPF