Home >Web Front-end >JS Tutorial >JavaScript method to achieve global matching and replacement_javascript skills

JavaScript method to achieve global matching and replacement_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:02:091419browse

The replace function is used to replace strings in JavaScript, but during actual use, it is found that this function will only replace the first matched character, which is very uncomfortable. In the PHP language, replace can Implement 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:

Copy code The code is as follows:

str.replace(/www.baidu.com/g,'www.jb51.net');

or:

Copy code The code is as follows:

str.replace(new RegExp('www.baidu.com','gm'),'www.jb51.net');

Replace all www.baidu.com in str characters with www.jb51.net

(2) Expand the js function library yourself and create your own function replaceall method to achieve global matching and replacement. As follows:

Copy code The code is as follows:

String.prototype.replaceall=function(s1,s2){
Return this.replace(new RegExp(s1,"gm"),s2);
}

This actually also 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):

Copy code The code is as follows:

str.replace('www.baidu.com','www.jb51.net');

The above is the entire content of this article, I hope you all like it.

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