To replace all occurrences of a substring in a string using regular expression in JavaScript, you can use the replace
method with a regex pattern and the g
flag.
In this example,
str
.replace
method on str
with a regex pattern matching "Hello" and replace it with "Hi" using the g
flag.replace
method returns a new string with all occurrences replaced.let str = "Hello World Hello";
let newStr = str.replace(/Hello/g, "Hi");
console.log(newStr);
Hi World Hi
In this example,
str
.replace
method on str
with a regex pattern matching digits (\d) and replace them with 'Y' using the g
flag.replace
method returns a new string with all occurrences replaced.let str = "Hello123World789";
let newStr = str.replace(/\d/g, "Y");
console.log(newStr);
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in JavaScript language with well detailed examples.