Home > Article > Web Front-end > js replace() text replacement you don't know_javascript skills
The text replacement function replace is applied here. Its general syntax is probably familiar to everyone. Now let’s introduce the situation when its second parameter is a function.
When I posted this function in the group today, someone responded quickly and said that the regular expression above was written incorrectly "/-(w)/ g", and then he quickly understood that his doubt was about this "()". In fact, this bracket is very necessary:
(x) matches x and saves x in variables named $1, $2...$9. In fact, it adds an index to it to facilitate subsequent calls. If you do not add these brackets, an error will occur:
Okay, let’s introduce the meaning of function parameters. Why can this function achieve the specified function?
ECMAScript v3 stipulates that the parameter replacement of the replace() method can be a function instead of a string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself.
It seems a bit annoying, for example:
That is to say, call it. In fact, the strMatch value above is -r, which is the string matching the regular pattern (The first parameter of this function is the string matching the pattern ),
The value of p1 above is r, which refers to the r immediately following - (The next parameter is a string matching the subexpression in the pattern ), which is the index we specify ——“(w)”.
Okay, I think it will be clear what this function is going to do in the future. Haha, that’s it. Additional suggestions are welcome .