How to Replace All Occurences of a String in Javascript?
In JavaScript, you can replace all occurrences of a string using the replace()
method with the regular expression (regex) global modifier /g
.
Here is an example using the replace()
method and regex /g
modifier to replace all occurrences of a string:
let myString = "Hello World, Hello World";
// Replace "Hello" with "Hi" globally using regex /g modifier
let replacedString = myString.replace(/Hello/g, "Hi");
console.log(replacedString); // "Hi World, Hi World"
In this example, the replace()
method replaces all occurrences of the string "Hello"
with "Hi"
by adding the /g
regex global modifier at the end of the regular expression pattern.