How to replace all occurrences of a string in Javascript

(Last Updated On: February 10, 2020)

I have pretty much resigned myself to the fact that in Javascript, there are really only two ways to do a proper search and replace.

Firstly, we need a base string to start manipulating, so let’s create our test subject:

var ourString = "This is a great string and we love it";

So now the options are as follows, replace, regular expression replace and split/join.

Javascript Replace

ourString.replace(" ", "-")

"This-is a great string and we love it"

As we can see with this method, it only replaces single occurrences in the string, which may be what you are trying to achieve, but it certainly wasn’t for this case!

Let’s try with a word now, it appears to work well, but that’s because we only had one occurrence yet again, so didn’t notice the problem!

ourString.replace("great", "amazing")

"This is a amazing string and we love it"

Javascript Regular Expression Replace

ourString.replace(/ /g, "-")

"This-is-a-great-string-and-we-love-it"

This works pretty well, because of the addition of the g flag, which means global, or “apply the condition in every matched occurrence.

This is the most recommended method and what I like to use personally.

Let’s try it with our previous “great” and “amazing” swap out:

ourString.replace(/great/g, "amazing")

"This is a amazing string and we love it"

As can be seen, we get the same output as our single occurrence example above. So this means we can use it for both single and multiple instance replacements/matching. Yet another reason to use it all the time!

While we’re looking into this, there is another option available to us, which I mentioned at the beginning of this post.

Javascript Split/Join

Another option you have available to you is that of the split and join combo.

ourString.split(" ").join("-")

"This-is-a-great-string-and-we-love-it"

Leave a Reply

Your email address will not be published.