how JavaScript implements global matching and substitution
This article mainly introduces the JavaScript implementation of the global matching and replacement method summary, very simple and practical, the need for small partners can refer to.
The Replace function is used in the JavaScript substitution string, but it is very unpleasant to find that the function replaces the first character that was matched in the actual use, and in the PHP language, replace is a global match and is replaced. No way, careful study, found that there are other ways to achieve global matching and replacement.
(1) In fact, the replace itself can also achieve this function, but to pass the regular form of the parameter G, 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 all www.baidu.com in the str character with Www.jb51.net
(2) Expand the JS function library, and replaceall the function of global matching and substitution by the method of self creation function. As follows:
The code is as follows:
String.prototype.replaceall=function (S1,S2) {
Return This.replace (New RegExp (S1, "GM"), S2);
}
This is actually the use of the idea of method one. Examples are as follows (this also implements the same function as above, but it is more intuitive than the method):
The code is as follows:
Str.replace (' www.baidu.com ', ' www.jb51.net ');
The above mentioned is the entire content of this article, I hope you can enjoy.