Home >Web Front-end >JS Tutorial >javascript regular expression trigger function for advanced replacement_javascript skills

javascript regular expression trigger function for advanced replacement_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:32:35983browse

Under normal circumstances, we may use regular expressions to replace text:

Copy code The code is as follows:

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

We can use functions to define advanced replacements instead of a simple string. For example:


The execution result is:


If we know the delivery The principle of the parameter rules will be very clear. In fact, if a submatch is defined in the regular expression, the length of the parameter will change with the number of submatches. If no submatch is defined, the length is fixed. . The rules for passing parameters are:

Matches the string itself
All submatches (if defined) <script> function reverseMatch(str) { return str.split('').reverse().join(''); } var a = "www jb51 net"; a=a.replace(/\w+/g, reverseMatch); alert(a); </script> Matches the position of the string in the original string