DEV Community

Sobhan Dash
Sobhan Dash

Posted on

Replace all occurrences of a String using JavaScript

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);
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

For older browsers:

src.split('replace').join('keep');
Enter fullscreen mode Exit fullscreen mode
src.split(/\d+/).join('keep');
Enter fullscreen mode Exit fullscreen mode