How to use the javascript string replace

If you are having problems changing a string in the text. We can use the replace() method.

What is the replace() method?

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Here is an example:

var str = "Replace here!!";
var res = str.replace("here", "");

But the replace method only executes once. So, if in case they want to replace all, how to do it. Below is one way

String.prototype.replaceAll = function(search, replace) {
     return this.replace(new RegExp(search, 'g'), replace);


Add a Comment

Your email address will not be published. Required fields are marked *