replace() method and
replace() method accepts the two arguments, the first one is
regex and the second one is
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
- The regex
/fun/gwe used a
gflag so that it can replace the
funvalue 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
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
i flag will replace both
Fun in a given string.
Let’s see, how can we use
join() methods to replace all occurrences of a string.
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
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"