JavaScript Regular expression trigger function for advanced substitution _javascript Tips

Source: Internet
Author: User
In general, we might use regular expressions to replace text:
Copy Code code as follows:

var a = "ABC123AXC";
A.replace (/a.c/g, ' ZZ ');

We can use functions to define advanced substitutions, rather than a simple string. Like what:
<script> function Reversematch (str) {return str.split ("). Reverse (). Join ("); var a = "www jb51 net"; A=a.replace (/\w+/g, Reversematch); alert (a); </script> [/code] Execution results are: <div class= "codetitle" ><span><U> copy code </U></span> code as follows: </div><div class= "Codebody" id= "code91699" > www 15bj ten
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

We see that when a regular expression produces a match at a time, it triggers the substitution function and passes the matching string as a parameter to the replacement function. When a submatch is defined in a regular expression, even more advanced things can be done, and the substitution function can be processed according to different child matches. For example, we want to convert some of the specified entity code in a Web page to a special character:
[Code]
var entity = {
quot: ' "',
LT: ' < ',
GT: ' > '
};
function Deentityify (A, b) {
var r = Entity[b];
return typeof r = = ' String '? r:a;
}
var a = "<a href=" http://jb51.net/">";
A.replace (/&) ([^&;] +);/g, deentityify);

The results of the execution are:

<a href= "http://jb51.net/" >
If we knew the rules for passing parameters, we would know the rationale. In fact, if you define a child match in a regular expression, the length of the argument changes with the number of child matches, and if no child matches are defined, the length is fixed. The rules for passing parameters are:

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.