How to implement global match and replace in javascript

Source: Internet
Author: User

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.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.