Replace all in JavaScript

JavaScript is very detailed language and have every small functions needed to complete your task. But some time we have some task for which javascript have function but still not complete in itself.

Here we will discuss one of that function. While working on your project may be you have faced the same issue. Replacing a text or any character is very common task in JavaScript and we have function for it that is replace which will replace your character pattern from your given character set with your new characters.
Example

<script>
  var str = "Visit Microsoft!";
  var res = str.replace("Microsoft", "GrowYour GK");// result: Visit GrowYour GK!
</script>

But JavaScript replace function has limitation, that is, it will replace the only first occurrence of your character set.
Example

<script>
  var str = "Visit Microsoft Microsoft Microsoft!!";
  var res = str.replace("Microsoft", "GrowYour GK");// result: Visit GrowYour GK Microsoft Microsoft!
</script>

So, If you want to replace all occurrence of your character set you need replaceall function which is not exist in JavaScript.

ReplaceAll in JavaScript

There are basically two ways to do this:

Regular Expression Based Implementation
<script>
  String.prototype.replaceAll = function(search, replacement) {    
    var target = this;    
    return target.replace(new RegExp(search, \'g\'), replacement);
  };
</script>
Split and Join (Functional) Implementation
<script>
  String.prototype.replaceAll = function(search, replacement) {    
    var target = this;    
    return target.split(search).join(replacement);
  };
</script>

Here I have add replaceAll method in JavaScript core String object. It will behave like inbuilt function of string Object.

Syntax to use!

<script>
  var str = "Visit Microsoft Microsoft Microsoft Microsoft!";
  var res = str.replaceAll("Microsoft", "GrowYour GK");
  // result: Visit GrowYour GK GrowYour GK GrowYour GK GrowYour GK!
</script>

Feel free to ask any query if you have at websolution4u.