Some tips for using replace in Javascript Regular Expressions.

Source: Internet
Author: User

Regular Expressions are often used, but they are basically used to verify the rationality of a string. For example:

VaR M = "12345 ";

VaR n =/^/d + $ /;

If (N. Test (M) Alert ('OK ');

Today I have read an example about using regular expressions in the replace method, which is very valuable and can be easily implemented, such as the lenb and trim methods.

I Want To sum up not this, but replace the pattern with $ in replace, for example:

VaR M = eval ("/(northsnow) +/g ");

VaR n = "I am northsnow, I come from Jilin ";

VaR t = n. Replace (M, "<B> $1 </B> ");

Alert (N );

The result is as follows: I am <B> northsnow </B>, I come from Jilin ";

The matching results in the brackets are extracted and put into the $ variable. $1 stores the matching of the first pattern, $2 stores the matching of the second pattern, and so on.

For example:

VaR M = "northsnow is a good man ";

VaR n = M. Replace (/s) ([A-Z] +)/g, "$1 ")

Result: northsnow

VaR n = M. Replace (/s) ([A-Z] +)/g, "$2 ")

Result: northsnowisagoodman

In addition, there is a/num that can be used. The num here is an integer, which indicates that the num-th mode is put here.

If (.)/1, it indicates two consecutive repeated characters.

If (.)/D */1 represents two identical characters with N numbers in the middle, N> = 0

Here is an example. As long as you have mastered the skills, you can accumulate experience through practice.

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.