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