Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Replacing multiple instances of a string inside another string in JavaScript

March 17, 2020
JavaScript

Let’s say we have a variable, text, assigned to a string:

let text = "the cat sat on the mat";

We want to replace the word “the” with the word “no”.

A JavaScript string has a nice replace method that we can use to do this. So, let’s give this a try:

text = text.replace("the", "no");

The text variable now contains the value “no cat sat on the mat”. This perhaps isn’t what we’d hoped for - only the first “the” has been replaced.

The first, parameter in the replace method can actually be a regular expression which we can use to specify that we want to replace all the instances of the matched word:

text = text.replace(/the/g, "no");

The g at the end of the regular expression tells the replace method to match all instances.

So, the text variable now contains the value “no cat sat on no mat”. Great - we managed to replace all the instances of “the” with “no”!

Let’s look at a slightly different example now:

let text = "The cat sat on the mat";

Again, we want to replace all the instances of the word “the” with “no”. However, this time the two instances of “the” are in different cases - “The” and “the”.

So, just doing the following:

text = text.replace(/the/g, "no");

… will give us “The cat sat on no mat”.

Not quite what we wanted!

The solution is simple though:

text = text.replace(/the/gi, "no");

We have extended the regular expression and specified a case insensitive match with i.

So, the text variable now contains the value “no cat sat on no mat”.

Nice!

Below is a working example in CodePen:

Open working example

Did you find this post useful?

Let me know by sharing it on Twitter.
Click here to share this post on Twitter
You might find some of my other posts interesting:
Upgrading npm dependencies

Want more content like this?

Subscribe to receive notifications on new blog posts and courses

Required
© Carl Rippon
Privacy Policy