Js USES regular methods to implement full ReplaceAll substitution

  • 2020-03-30 03:33:36
  • OfStack

JS strings have a replace() method. But this method only replaces the first string that matches. The following cases:


<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>

<BODY>
<script>
var str = "wordwordwordword";
var strNew = str.replace("word","Excel");
alert(strNew);
</script>
</BODY>
</HTML>

If you want to replace everything, JS doesn't provide a method called replaceAll. Use regex to achieve the effect of Replace:

Str.replace (/word/g,"Excel")g means: perform a global match (find all matches instead of stopping after the first one is found).


<HEAD>
<TITLE> New Document </TITLE>
<script>
function replaceAll(str)
{
if(str!=null)
str = str.replace(/word/g,"Excel")
return str;
}
</script>
</HEAD>

<BODY>
<script>
var str = "wordwordwordword";
var strNew = str.replace("word","Excel");
strNew = replaceAll(str);
alert(strNew);
</script>
</BODY>
</HTML>

There is a similar way to write the above:

Str.replace (new RegExp("word","gm"),"Excel")g performs global matching (looking for all matches instead of stopping after the first one is found).

M performs multi-line matching.

In addition, we can also add the prototype method of the Stirng object:


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

This allows you to use replaceAll just like you would with the replace method

STR. ReplaceAll (" word ", "Excel"); So to summarize, three ways

1. STR. Replace (/ oldString/g, newString)

2. STR. Replace (new RegExp (oldString, "gm"), and newString)

3. Add the String object prototype method replaceAll


Related articles: