Home  >  Article  >  Web Front-end  >  js uses regular expressions to implement ReplaceAll replacement method_javascript skills

js uses regular expressions to implement ReplaceAll replacement method_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:052338browse

JS strings have the replace() method. But this method will only replace the first matched string. For example:

<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 all, JS does not provide a method like replaceAll. The effect of Replace can be achieved using regular tables:

str.replace(/word/g,"Excel")

g means: perform a global match (find all matches instead of stopping after the first match 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>

The above writing method has a similar writing method:

str.replace(new RegExp("word","gm"),"Excel")

g performs a global match (finds all matches instead of stopping after the first match is found).

m performs multi-line matching.

In addition, you 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 way you can use replaceAll just like using the replace method

str.replaceAll("word","Excel");

To summarize, there are three ways

1. str.replace(/oldString/g,newString)

2. str.replace(new RegExp(oldString,"gm"),newString)

3. Add String object prototype method replaceAll

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn