How to Replace All Occurences of a String in Javascript Full Tutorial For Beginners

 

 

In the latest versions of most popular browsers, you can use replaceAll as shown here:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

 

 

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

 

 

For older/legacy browser support:


str = str.replace(/abc/g, '');

In response to comment:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

You could simplify it even more:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}

 

 

Say you want to replace all the ‘abc’ with ‘x’:

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

 

 

I like this method (it looks a little cleaner):

text = text.replace(new RegExp("cat","g"), "dog"); 

Leave a Reply