There are mainly two methods, using which we can replace all occurrences of a string.
- The split & join method.
- The replace all approach.
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
Split & join method
Split & join are two separate methods and, we are going to use those as chained methods. Check the solution 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
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.
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.
For a reference, we can refer to this link for the most recent performance check https://jsperf.com/replace-all-vs-split-join