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

js uses regular expressions to implement ReplaceAll replacement method_javascript skills

WBOY
Release: 2016-05-16 16:39:05
Original
2369 people have browsed it

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>
Copy after login

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")
Copy after login

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>

Copy after login

The above writing method has a similar writing method:

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

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); 
}
Copy after login


This way you can use replaceAll just like using the replace method

str.replaceAll("word","Excel");
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template