Categories
JavaScript Answers

How to Replace All Occurrences of a Javascript String?

Spread the love

Replacing all occurrences of a string is something that we often have to do in a JavaScript app.

In this article, we’ll look at how to replace all occurrences of a string in a JavaScript app.

String.prototype.replaceAll

The replaceAll method is a new method that’s available as part of JavaScript strings since ES2021.

It’s supported by many recent browsers like Chrome, Edge, or Firefox.

To use it, we write:

const result = "1 abc 2 abc 3".replaceAll("abc", "def");

The first argument is the string we want to replace.

And the 2nd argument is the string we want to replace it with.

Therefore, result is '1 def 2 def 3' .

Split and Join

We can also split a string by the string that we want to replace and call join with the string that we want to replace the original string with,

For instance, we can write:

const result = "1 abc 2 abc 3".split("abc").join("def");

to split a string with 'abc' as the separator and call join with 'def' .

And we get the same result returned.

Regex Replace

We can replace a string with the given pattern with a new string.

For instance, we can write:

const result = "1 abc 2 abc 3".replace(/abc/g, 'def');

to replace all instances 'abc' with 'def' .

The g flag means we look for all instances with the given pattern.

We can also use the RegExp constructor to create our regex object:

const result = "1 abc 2 abc 3".replace(new RegExp('abc', 'g'), 'def');

While Loop and Includes

We can use the includes method to check if a string has a given substring.

So if it has a given substring, includes will return true .

Therefore, we can use it with the while loop to replace all instances of a substring with a new one by using includes in the condition.

For instance, we can write:

let str = "1 abc 2 abc 3";  
while (str.includes("abc")) {  
  str = str.replace("abc", "def");  
}

We use let so that we can reassign the value.

The only downside is that we have to mutate the str variable.

Conclusion

There are many ways to replace all instances of a substring with another one in JavaScript.

The newest and easier way to replace all substrings is to use the replaceAll method, which comes with ES2021 and is available with most recent browsers.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.