In the previous article, we introduced to you an example of the replaceall method in jQuery. I believe that my friends have a better understanding of the use of replaceall, so today we will continue to introduce to you about JavaScriptAn example of implementing replaceall global matching and replacement!
ReplaceStringin javascript uses the replacefunction, but during actual use, it is found that this function will only replace the first matched character. This makes people very unhappy. In the PHP language, replace can achieve global matching and replacement. No way, after careful study, I found that there are other ways to achieve global matching and replacement.
(1) In fact, replace itself can also achieve this function, but it needs to add a parameter g in a regular form, for example:
str.replace(/www.baidu.com/g,'www.php.cn');
or:
str.replace(new RegExp('www.baidu.com','gm'),'www.php.cn');
Replace all www.baidu.com in str characters with php.cn
(2) Expand the js function library yourself and create your own function replaceall method to achieve global matching and replace the function. As follows:
String.prototype.replaceall=function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); }
This actually uses the idea of method one. An example is as follows (the same function as above is also implemented here, but it is more intuitive than method one):
str.replace('www.baidu.com','www.php.cn');
Summary:
This article introduces to you through examples the JavaScript implementation of replaceall global matching and replacement. I believe that my friends also have a certain understanding of this. I hope it will be helpful to your work!
Related recommendations:
The above is the detailed content of JavaScript implements replaceall global matching and replacement examples. For more information, please follow other related articles on the PHP Chinese website!