js method to achieve replaceAll

js would have been replace method, see the description of w3school:

  replace () method for replacing some characters other characters, or alternatively a substring match the positive expression in using string.

grammar:

  stringObject.replace(regexp/substr,replacement)

  The first argument is a string or a regular expression, the second parameter is a string or a function to generate a string.

Note emphasis:

  If the flag has global regexp g, the replace () method will replace all substring matching. Otherwise, only replace the first matching substring.

Example:

var str = "dogdogdog";
var str2 = str.replace("dog","cat");
console.log(str2);

Here only the first dog string Alternatively, output: catdogdog.

js is no replaceAll method, then how to achieve it replaces all strings match that achieved in the js replaceAll method:

1. Using regular expressions have a global flag g

var str = "dogdogdog";
var str2 = str.replace(/dog/g,"cat");
console.log(str2);

Alternatively achieve all matching strings, output is: catcatcat.

The method defined regular expression using another 2 g of having a global flag

var str = "dogdogdog";
var str2 = str.replace(new RegExp("dog","gm"),"cat");
console.log(str2);

The output above embodiment. Where g denotes global matching execution, m represents perform multiple matching.

3. The method of prototype object is added to the string the replaceAll ()

String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

This method can be used replaceAll the same as using the replace method:

var str = "dogdogdog";
var str2 = str.replaceAll("dog", "cat");
console.log(str2);

The output above embodiment.
Personally I recommend using the third method.

Guess you like

Origin www.cnblogs.com/henuyuxiang/p/11609088.html