To replace all occurrences of a substring in a string in JavaScript, you can use the replace
method with a regular expression.
In this example,
str
.replace
method on str
with a regular expression to match all occurrences of the substring and the replacement string as arguments.replace
method returns a new string with all occurrences of the substring 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 regular expression to match all occurrences of the character and the replacement character as arguments.replace
method returns a new string with all occurrences of the character replaced.let str = "Hello World Hello";
let newStr = str.replace(/o/g, "X");
console.log(newStr);
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in JavaScript language with well detailed examples.