Anjan Dutta

Replace all occurrences of a string in javascript

Replace all occurrences of a string in javascript

Writing a string operation is simple and easy in Javascript. There are several string functions available in Javascript. So, it is less often when we write any custom function for such operations.

Today, in this article, I am explaining how to replace all occurrences of a string in Javascript. I am also going to describe multiple methods and performance comparison between each approach.

There are two ways to replace all occurrences of a string.

  1. The split & join method.
  2. The replace all approach.

Sample problem

Let’s assume we have an example string like below.

str = "The quick brown fox jumped over the lazy brown dog";

We have two 'the' in the sentence and we want to replace that with an 'a'. And we want to replace all occurrences of 'the' in the given string using javascript.

Split & join method

Split & join are two separate methods and, we are going to use those as chained methods.

Check the example below.

var str = "The quick brown fox jumped over the lazy brown dog";
str = str.toLowerCase().split('the').join('a');
console.log(str);
// a quick brown fox jumped over a lazy brown dog

‘The’ and ‘the’ are two different words for the Javascript compiler. So, the first part str.toLowerCase() is replacing all upper cases to lower case.

The second part of the operation .split('the') is splitting the string into multiple array elements. And after splitting the array elements look like below.

0: ""
1: " quick brown fox jumped over "
2: " lazy brown dog"

Our third part of the operation .join('a') will then take all the elements and glue those up using the provided key, which is 'a' in our scenario.

Replace all approach

The replace-all approach is comparatively easy than the split & join method. See the code below.

var str = "The quick brown fox jumped over the lazy brown dog";
str.toLowerCase().replace(/the/g, 'a');
console.log(str);
// a quick brown fox jumped over a lazy brown dog

As we can see in the above example, the .replace() method takes two parameters. The first one is a regex to match and find all the occurrences of the string to be replaced.

The second parameter is the word which would replace all the string occurrences.

Performance comparison

From the performance point, the second approach is much faster than the first approach. But we have seen this was not always the same. With different browser engine updates, the performance also varies over time.