Javascript Regular Expressions trigger functions for advanced replacement

Source: Internet
Author: User

In general, we may use a regular expression to replace the text:
Copy codeThe Code is as follows:
Var a = "abc123aXc ";
A. replace (/a. c/g, 'zz ');

We can use functions to define advanced replacement instead of a simple string. For example:
[/Code] The execution result is: <U> copy code </U> the code is as follows: www 15bj ten
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
We can see that when a regular expression generates a match, the replacement function is triggered and the matching string is passed as a parameter to the replacement function. When a regular expression defines submatch, it can even do more advanced tasks. The replacement function can process different submatches accordingly. For example, we want to convert some specified entity code in the webpage into special characters:
[Code]
Var entity = {
Quot :'"',
Lt: '<',
Gt: '>'
};
Function deentityify (a, B ){
Var r = entity [B];
Return typeof r === 'string '? R:;
}
Var a = "<a href =" http://jb51.net/"> ";
A. replace (/& ([^ &;] +);/g, deentityify );

The execution result is:

<A href = "http://jb51.net/">
If we know the rules for passing parameters, we will be very clear about the principle. In fact, if a child match is defined in a regular expression, the length of the parameter will change with the number of child matches. If a child match is not defined, the length is fixed. The rule for passing parameters is:

Match string itself
All child matches (if defined)
Match the position of the string in the original string

Related Article

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.