Replace all occurrences of a substring in a string using JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 |
String.prototype.replaceAll = function(search, replacement) { return this.replace(new RegExp(search, 'g'), replacement); }; const str = 'Hello World 123'; console.log(str.replaceAll(" ", "")); /* Output: HelloWorld123 */ |
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:
|
1 2 3 4 5 6 7 8 9 10 |
String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; const str = 'Hello World 123'; console.log(str.replaceAll(" ", "")); /* Output: HelloWorld123 */ |
That’s all about replacing all occurrences of a substring in a string using JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)