How to implement global match and replace in javascript
How to implement global match and replace in javascript
This article mainly introduces the summary of the method for implementing global matching and replacement in javascript, which is very simple and practical. If you need it, you can refer to it.
The replace function is used to replace strings in javascript, but in actual use, it is found that this function only replaces the first character to be matched, which makes people very uncomfortable, in php, replace implements global matching and replacement. No way. After careful research, we found that there are other ways to achieve global matching and replace it.
(1) In fact, replace itself can also implement this function, but you need to add a parameter g in the form of a regular expression, for example:
The Code is as follows:
Str. replace (/www.baidu.com/g,'www.jb51.net ');
Or:
The Code is as follows:
Str. replace (new RegExp ('www .baidu.com ', 'GM'), 'www .jb51.net ');
Replace www.baidu.com with www.jb51.net.
(2) Expand the js function library and use the replaceall method to implement global matching and replacement. As follows:
The Code is as follows:
String. prototype. replaceall = function (s1, s2 ){
Return this. replace (new RegExp (s1, "gm"), s2 );
}
This is actually using method 1. For example ):
The Code is as follows:
Str. replace ('www .baidu.com ', 'www .jb51.net ');
The above is all the content of this article. I hope you will like it.