2 Ways to Replace All Occurrences of a String in JavaScript

2 Ways to Replace All Occurrences of a String in JavaScript

If you have ever used the replace method on a JavaScript string, then you know that it does not quite work like other programming languages. The problem with replace method in JavaScript is that it only replaces the first occurrence of a string. In this post, I will show you 3 different ways to replace all occurrences of a string in JavaScript.

1. Use Global Modifier to Replace All Occurrences

In order to replace all occurrences of a string in JavaScript, you need to pass in a regular expression with a global modifier (/g) to the replace method.

var value = 'You cannot end a sentence with because because because is a conjunction';

var newValue = value.replace(/because/g, 'message');

console.log(newValue); // You cannot end a sentence with message message message is a conjunction

It is worth noting that you need to escape all special characters in the regular expression. Take the following example:

var value = 'You cannot end a sentence with because| because...';

var newValue = value.replace(/because|/g, 'message');

console.log(newValue) // messageYmessageomessageumessage messagecmessageamessagenmessagenmessageomessagetmessage messageemessagenmessagedmessage messageamessage messagesmessageemessagenmessagetmessageemessagenmessagecmessageemessage messagewmessageimessagetmessagehmessage messagemessage|message messagemessage.message.message.message

Well, I was not expecting the output above.. | is a special character that I did not escape inside the call to replace method. We just need to escape the special character with a \ backslash, as shown below:

var value = 'You cannot end a sentence with because| because...';

var newValue = value.replace(/because|/g, 'message');

console.log(newValue) // You cannot end a sentence with message because...

You must escape all special characters -/\^$*+?.()|[]{}) in order for replace all to work properly.

2. split() and join() to Find and Replace All Occurrences

If you don’t want to escape special characters while replacing all occurrences of a string in JavaScript, you can combine split and join methods.

var value = 'You cannot end a sentence with because| because...';

var newValue = value.split("because|").join("message");

console.log(newValue) // You cannot end a sentence with message because...

How does this work?

split() method returns an array of substrings using the separator. Since we define the separator to be because|, the split returns an array where the elements are the substrings before and after each occurrence of the separator.

value.split("because|")
// ["You cannot end a sentence with ", " because..."]

We then use join on the array to stitch each element of the array back together. While joining, the replacement text provided will be used to fill in the gaps.

["You cannot end a sentence with ", " because..."].join("message")
"You cannot end a sentence with message because..."

Summary

Let’s recap what we have discussed in this post. There are two ways to replace all occurrences of a string in JavaScript:

  1. Use regular expression with global modifier /g
  2. Combine split and join methods to find and replace all

Do you know other techniques to replace all occurrences of a string in JavaScript? Drop a comment below!

Umut Esen

Umut is a certified Microsoft Certified Solutions Developer and has an MSc in Computer Science. He is currently working as a senior software developer for Royal London. He is the primary author and the founder of onthecode.

Leave a Reply

Close Menu

Free Template

Get your Angular Material application template to kick-start your next project.