To replace all occurrences of a string in JavaScript, you can use the replace()
method of a string along with a regular expression with the global flag /g
. Here’s an example:
let str = "Hello, world! Hello, John! Hello, Jane!"; let newStr = str.replace(/Hello/g, "Hi"); console.log(newStr); // "Hi, world! Hi, John! Hi, Jane!"
In the example above, the regular expression /Hello/g
matches all occurrences of the string “Hello” in the original string str
. The replace()
method replaces each match with the string “Hi” and returns a new string newStr
.
Note that the global flag /g
is necessary to replace all occurrences of the string. Without the global flag, the replace()
method would only replace the first occurrence of the string.
In Summary , replacing a single time, use:
const res = str.replace('Hello', "Hi");
For replacing multiple times, use:
const res = str.replace(/Hello/g, "Hi")
Replace all commas with underscore in javascript:
let str = "Hello,How,are,you"; let newStr = str.replace(/,/g, "_"); or let newStr = str.replaceAll(",", "-"); console.log(newStr); // "Hi_How_are_you"