Use replace
with a regular expression with the global modifier for better browser support. (Check the browser compatibility table on MDN to see which version of each browser started supporting the replaceAll
method.)
let string = ":insertx: :insertx: :inserty: :inserty: :insertz: :insertz:";
let newstring = string.replace(/:insertx:/g, 'hello!');
console.log(newstring);
For a more generic solution, we can escape regular expression metacharacters and use the RegExp
constructor. You could also add the function to String.prototype
as a polyfill.
(It is necessary to escape the string to replace so that characters that have special meanings in regular expressions will be interpreted literally, e.g. .
will refer only to actual dots rather than any character.)
//Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function replaceAll(str, match, replacement){
return str.replace(new RegExp(escapeRegExp(match), 'g'), ()=>replacement);
}
console.log(replaceAll('a.b.c.d.e', '.', '__'));
console.log(replaceAll('a.b.c.d.e', '.', '$&'));
A specification-compliant shim can be found here.