Replace all Occurrences of a String in JavaScript
JavaScript has a lot of useful methods that you can use to manipulate strings. For example, there is a String.replace()
method to replace a simple substring with another string. One problem with this method is that it only replaces the first occurrence of the word or substring. In this tutorial, we will learn about different methods which can be used to replace all occurrences of a substring inside the main string.
Using RegExp With the ‘g’ Flag to Replace all Occurrences of a String
Since String.replace()
does not replace all the occurrences of a simple substring inside another string. You can pass the word or substring as a regular expression with the g
flag attached to it. This way the string will replace all occurrences of the given word or substring. Here is an example:
JavaScript
var sentence = "I like apples a lot. You ate all my apples.";
var find = /apples/g;
var replacement = 'bananas';
var result = sentence.replace(find, replacement);
// Output — I like bananas a lot. You ate all my bananas.
console.log(result);
This regular expression based solution works perfectly if you want to search for all occurrence of a string and replace it with something else. However, there is one important thing that you need to keep in mind. This method will give unexpected results if the find
string contains a special regular expression character. Here is an example in which replaces all occurrences of “app|les” inside the main string breaks things. This is because pipe is a special character in regular expressions.
JavaScript
var sentence = "I like app|les a lot. You ate all my app|les.";
var find = /app|les/g;
var replacement = 'bananas';
var result = sentence.replace(find, replacement);
// Output — I like bananas|bananas a lot. You ate all my bananas|bananas.
console.log(result);
You can escape the pipe (|
) character inside the regular expression by using |
. This will make sure that the replacement is added only once.
JavaScript
var sentence = "I like app|les a lot. You ate all my app|les.";
var find = /app\|les/g;
var replacement = 'bananas';
var result = sentence.replace(find, replacement);
// Output — I like bananas a lot. You ate all my bananas.
console.log(result);
Using split() and join() to Replace all Occurrences of a String
If you want to avoid escaping the special characters that might get passed in the regular expression we used earlier to replace all occurrences of a string, you should consider using the String.split() and Array.join() methods together.
The String.split()
method splits the calling string into an array of substrings, using the specified separator string to determine where to make each split. This separator string will be the substring that you want to replace.
The Array.join()
method joins all the elements of an element together using the specified glue string and returns the combined string. This glue will be the substring that you want to be the replacement of the old substring in the main string.
In the following example, we will use these methods together to replace all occurrences of “apples” with “bananas”.
JavaScript
var sentence = "I like apples a lot. You ate all my apples.";
var find = "apples";
var replacement = "bananas";
var result = sentence.split(find).join(replacement);
// Output — I like bananas a lot. You ate all my bananas.
console.log(result);
With this method, you will no longer have to worry about escaping any special regex characters like you had to in the previous section.
JavaScript
var sentence = "I like app|les a lot. You ate all my app|les.";
var find = "app|les";
var replacement = "bananas";
var result = sentence.split(find).join(replacement);
// Output — I like bananas a lot. You ate all my bananas.
console.log(result);
Using indexOf() Multiple Times to Replace all Occurrences of a String
The String.indexOf() method returns the index of the given substring within the calling string. This means that if the main string contains multiple occurrences of a substring, you can just keep calling String.replace()
until the String.indexOf()
method finally returns -1.
JavaScript
var sentence = "I like apples a lot. You ate all my apples.";
var find = "apples";
var replacement = "bananas";
var result = sentence;
while (result.indexOf(find) > -1) {
result = result.replace(find, replacement);
}
// Output — I like bananas a lot. You ate all my bananas.
console.log(result);
One major problem with this solution is that you can get stuck in an infinite loop if the find
string can be found inside the replacement
string. For example, if you were to use this method to replace “apples” with “pineapples”, this technique will trigger an infinite loop. This is because the method will keep returning an index greater than -1 when we search for “apples” as “pineapples” also contains “apples”.
Quick Summary
Let’s recap everything that we have covered in this tutorial.
- In order to replace all occurrences of a word in a string, you can simply use the inbuilt
String.replace()
method and provide the string you want to replace as a regex expression with theg
flag. The only problem with this solution is that you will have to escape all the special characters in thefind
string that you want to replace. - If you don’t want to deal with special regex characters, you can also use the
String.split()
andArray.join()
methods togehter to break the string using one substring and then joining it together using another substring. - If you want to use the
String.replace()
method to do the replacements but don’t want to use regex, you can just keep checking the existence of the subtring that you want to replace in the main string using theString.indexOf()
method. This will generally work fine but you will be stuck in an infinite loop if thereplacement
string contains thefind
string.
Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to replace all occurrences of a string in JavaScript.
Rate this post —