Advanced usage of JSReplace () _ javascript tips-js tutorial

Source: Internet
Author: User
This article introduces some advanced use methods of Replace () in js. If you need it, you can refer to the following: in many projects, we often need to use JS, the replace () method of js is required to modify some elements in front of the page.

If you frequently use "ABCABCabc". replace ("A", "B"), you should be clear that the final result of the modified statement is BBCABC. This method can only be replaced

The first matched element. What if I replace all? Use a regular expression:

"ABCABCabc". replace (/A/g, "B.
What if I want to replace A with?

Then you can use "ABCABCabc". replace (/a/ig, "B ");

Flag: the size of the I-ID ignore is ignored, the g-ID global is repeatedly searched, and the m-ID multi-row retrieval (this is not tested yet)

You can also use their combination. For example, the ig used above replaces all the IDs and ignores the case.

Regular regular expression:

The Code is as follows:


Var reg = new RegExp (/patten/flag)
Var strs = "". match (reg );


When the flag uses g, strs returns a string array.

If you want to match any one of multiple strings, you can use

The Code is as follows:


Reg = new RegExp (/abc | xyz/ig );

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.