How do I use JavaScript replace all to replace all occurrences of a string in JavaScript?

How do I use JavaScript replace all to replace all occurrences of a string in JavaScript?

Given a string:

string = “Test abc test test abc test test test abc test test abc”;

This seems to only remove the first occurrence of abc in the string above:

string = string.replace(‘abc’, ‘’);

How do I replace all occurrences of it?

Hi,

You can use the replace() method with a regular expression that includes the global flag (g) to replace all occurrences of the substring:

let string = "Test abc test test abc test test test abc test test abc";
string = string.replace(/abc/g, '');

Hi,

You can use the String.prototype.split() and Array.prototype.join() methods.

Another approach is to split the string by the target substring and then join it back without the substring:

let string = "Test abc test test abc test test test abc test test abc";
string = string.split('abc').join('');

If you are using a JavaScript version that supports it, you can directly use the replaceAll() method:

let string = "Test abc test test abc test test test abc test test abc";
string = string.replaceAll('abc', '');