Skip to content

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 ✌️

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.