How to Replace All Instances of a String in JavaScript

Abstract image used to represent 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 string. 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.

Postscript

June 2026: For current code, replaceAll() is a straightforward choice for literal text: "afternoon and afternoon".replaceAll("afternoon", "morning") returns "morning and morning". A string search treats characters such as . literally. The regex examples above remain useful for patterns, but escape any usersupplied text before putting it into a RegExp; otherwise its special characters become part of the pattern.

Looking for technical direction?

I support teams that need senior judgement on React, Next.js, headless CMS architecture, performance, migrations, and technical SEO.