JavaScript String.prototype.replaceAll
In JavaScript, we can’t replace the all occurance of substring in a string without use of global regex. In our previous post that is Replace all instances of a string in JavaScript we have shown how to replace with regex.
Now the JavaScript propose the new method String.prototype.replaceAll
. This gives the straight-forward way to replace all the instance of substring.
Syntax
String.prototype.replaceAll(searchValue, replaceValue)
let str = 'π¬ππ¬ππ¬π'; console.log(str.replace('π', 'π°')); //π¬π°π¬ππ¬π console.log(str.replaceAll('π', 'π°')); //π¬π°π¬π°π¬π°
When using a regular expression search value, it must be global.
'aabbcc'.replaceAll(/b/, '.'); //TypeError: replaceAll must be called with a global RegExp βΉοΈ 'aabbcc'.replaceAll(/b/g, '.'); //aa..cc π
What happens ifΒ searchValue
Β is the empty string?
'β½'.replace('', '_'); // β '_β½' 'β½β½β½'.replace(/(?:)/g, '_'); // β '_β½_β½_β½_' 'β½β½β½'.replaceAll('', '_'); // β '_β½_β½_β½_'
Resource
Happy Learning βοΈ