How to Replace All Instances of a String in JavaScript

Hero image for How to Replace All Instances of a String in JavaScript. Image by Paul Volkmer.
Hero image for 'How to Replace All Instances of a String in JavaScript.' Image by Paul Volkmer.

In frontend development, it's really common to find that you need to replace strings of text, from within another sting. Here, we take a quick look into using JavaScript replace() method, both with and without regular expressions.


Replacing Just a Single Instance

By default, the replace() method will only replace the first instance it comes across within a string. So, to replace only the first case of 'afternoon' with 'morning', but not any following instances of 'afternoon', your code would look something like this:

const text =  'This afternoon, I finished my latest project.  I will spend tomorrow afternoon with my daughters.';console.log(text.replace('afternoon', 'morning'));//=> 'This morning, I finished my latest project.  I will spend tomorrow afternoon with my daughters.'

Replacing Every Instance

In order to replace every instance of a string with another, we need to revert to using a regular expression, alongside the global modifier (/g):

const text =  'This afternoon, I finished my latest project.  I will spend tomorrow afternoon with my daughters.';console.log(text.replace(/afternoon/g, 'morning'));//=> 'This morning, I finished my latest project.  I will spend tomorrow morning with my daughters.'

Rather than using the inline regex method, you can also call the RegExp constructor function, which can be useful when you're working with much more complex examples where code readability is of concern. The following snippet is for all intents and purposes the longhand version of the one above:

const text =  'This afternoon, I finished my latest project.  I will spend tomorrow afternoon with my daughters.';console.log(text.replace(new RegExp('afternoon', 'g'), 'morning'));//=> 'This morning, I finished my latest project.  I will spend tomorrow morning with my daughters.'

And that's it! Using replace() is very simple and intuitive. If you want to learn more about using regular expressions or want to test your own, then I'd recommend you visit regex101.


Categories:

  1. Front‑End Development
  2. JavaScript