In the past, we had to do a lot of workaround for simply replacing the frequently appearing string or words in JavaScript.
Well, no more. The idea of this blog is to make you aware of the new function .replaceAll
//For legacy browsers, the following code replaced all occurrences.
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
But now we have the powerful function replaceAll, which matches the word and replaces it with a word.
It can match to a substr or, a regex for identifying what to replace.
const src = 'We replace all the occurrences by replacing the word with keep';
const replaced = src.replaceAll('replace', 'keep');
console.log(replaced);
// Outputs: This string keeps two occurrences of the substring keep
console.log(src)
//Outputs: We replace all the occurrences by replacing the word keep
The interesting thing is that the original string remains unchanged.
The function .replaceAll
is available in all major browsers since Firefox 77, Chrome 85, and Safari 13.1.
A general view of the function would be:
replaceAll(regexp, newSubstr)
replaceAll(regexp, replacerFunction)
replaceAll(substr, newSubstr)
replaceAll(substr, replacerFunction)
Are there any alternatives?
Sure there are.
Earlier, the replace function only replaced the first occurrence. So like I said above, we need to call it with a global flag until every word gets replaced.
When we use the regex with the g
flag, it works for legacy browsers as well.
const src = 'My favorite color of all colors is orange';
const replaced = src.replaceAll(/color/g, 'fruit');
console.log(replaced);
// Outputs: My favorite fruit of all fruits is orange
Similarly, we can use join and split methods to replace the words.
const src= 'Are we live? lively folks!';
const replaced = src.split('live').join('home');
console.log(replaced);
// Outputs: Are we home? homely folks!
That's it from my side. I learned a new function and wanted people to be aware of this.
Let me know if there are similar functions as replaceAll that can be used to replace our tedious ways!
Top comments (1)
For older browsers: