You are likely on this page for one of three reasons: 1) You have not yet seen that replaceAll has been implemented in all modern browsers, 2) You are targeting older browsers such as IE11 or 3) you have just discovered that replace only replaces the first occurrence in a string.
But it is true! With 90% usage coverage you can use replaceAll
rather than making your own replaceAll
implementation. Here is a small example with the numbers 1-20 in a string and replacing '1' with 'x':
var aString = '1234567891011121314151617181920';
var replacedString = aString.replaceAll('1','x');
console.log(replacedString); //Will be 'x23456789x0xxx2x3x4x5x6x7x8x920'
replaceAll
replaces all occurrences, it does not change the original string but returns a new one. It can replace more than one character just like replace
:
var aString = '1234567891011121314151617181920';
var replacedString = aString.replaceAll('12','xx');
console.log(replacedString); //Will be 'xx34567891011xx1314151617181920
You can also use regular expressions (regex):
var aString = '1234567891011121314151617181920';
var replacedString = aString.replaceAll(/12/g,'xx');
console.log(replacedString); //Will be 'xx34567891011xx1314151617181920
That is all there is to it, over the years I have seen many weird implementations of replaceAll
and I have probably been responsible for a couple of them myself. I am glad that there is an alternative now with good coverage!
Older browsers or pre node 15
If you do not have a built-in replaceAll
you can use a global regular expression with replace
instead:
var aString = '1234567891011121314151617181920';
var replacedString = aString.replace(/12/g,'xx');
console.log(replacedString); //Will be 'xx34567891011xx1314151617181920
Alternatively you can implement it using a polyfill and not worry about whether or not the browser or system has replaceAll
built-in.
That is all!
I hope you enjoyed this post, I for one am happy that replaceAll
now has wide support. Feel free to leave a comment down below with your thoughts!