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