How JavaScript implements global matching and substitution

Source: Internet
Author: User
Tags php language

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.