How to Replace All Occurrences of a String in JavaScript
In this tutorial, we are going to learn about how to replace the all occurrences of a string in JavaScript with the help of a replace()
method and split()
method.
Using the replace method
The replace()
method accepts the two arguments, the first one is regex
and the second one is replacement
value.
Example:
const str = "hello fun good morning fun morning fun etc";
//str.replace(regex, replacementvalue);
const replaced = str.replace(/fun/g,'');
console.log(replaced);
//Ouput--> hello good morning morning etc
In the above example, we are replacing the fun
from the following string with an empty value using replace()
method.
- The regex
/fun/g
we used ag
flag so that it can replace thefun
value at a global level instead of stopped replacing after the first occurrence.
If you want to replace case insensitive words in your string you can use i
flag.
const str = "hello fun good morning Fun morning fun etc Fun";
const replaced = str.replace(/fun/gi,'');
console.log(replaced); //hello good morning morning etc
This i
flag will replace both fun
and Fun
in a given string.
Using split and join methods
Let’s see, how can we use split()
and join()
methods to replace all occurrences of a string.
The split()
method splits the string where it finds the pattern
, and return the array of strings.
const str = "hello fun good morning Fun morning fun etc Fun";
const split = str.split('fun');
//split--> ["hello ", " good morning Fun morning ", " etc Fun"]
Now we need to combine the array of strings into a single string using the join()
method.
const final = split.join('');
//"hello good morning Fun morning etc Fun"
We can also add the replacement
value inside join()
method instead of empty quotes.
const str = "hello fun good morning Fun morning fun etc Fun";
const final = str.split('fun').join('king');
console.log(final);
//"hello king good morning Fun morning king etc Fun"