This post will discuss how to replace all occurrences of a substring in a given string using JavaScript.

There is no native replaceAll() method in JavaScript which replaces all matches of a substring by a replacement. This post provides an overview of some of the available alternatives to accomplish this.

1. Using Regular Expression

The general strategy for replacing a substring in the given string is with the replace() method. However, the replace() method only removes the first occurrence of the substring. The idea is to pass a RegExp object to the replace() method to replace all occurrences.

Here’s a working example with the regular expression defined in the replace() method.

Download  Run Code

2. Using Split() with Join() method

Another approach is to split the string using the given substring as a delimiter and then join it back together with the replacement string. This would translate to a simple code below:

Download  Run Code

That’s all about replacing all occurrences of a substring in a string using JavaScript.