- The simplest use of replace is:
var str = ' aaaaa9876b0000 '; str.replace (/a/g, ' a ');
- Sometimes we want to just add a specific character in a matching location:
var str = ' aaaaa9876b0000 '; Str.replace (/([0-9])/g, ' [$] ');
These results are:
AAAAA[9][8][7][6]B[0][0][0][0]
- If we want to make a mathematical calculation of the matching position, then we can change the second parameter to a function whose return value is the character to be changed in the corresponding position:
' abc123ba0c '. Replace (/([0-9])/g,function(m) {return 2*parseint (m)})
These results are:
abc246ba0c
So, what are the parameters of this function?
The first parameter represents a matching complete string, equivalent to/([0-9]) after the global execution of the Exec method of/g, as follows:
>var reg =/([0-9])/g
>reg.exec (' abc123ba0c ') ["1", "1"]>reg.exec (' abc123ba0c ') ["2", "2"]> Reg.exec (' abc123ba0c ') ["3", "3"]>reg.exec (' abc123ba0c ') ["0", "0"]
How many () regular expressions There are, and how many arguments can be followed by M, which represent the contents of the corresponding position in the above matching results.
After the parameters in these (), there is also a parameter that represents the starting point of all globally matched string m in the original string:
> ' abc123ba0c '. Replace (/([a-z]+) ([0-9]+)/g,function(M,P1,P2,P3,P4) {Console.log (m+ ' + p1 + ' +p2+ ' + 123 00 6
JavaScript String Object Method replace