When I was reading the jquery source code today, I found a problem that I had never noticed before, which is the problem when the second parameter of replace() is a function. I used to know that the second parameter of replace() can be a function, but I don’t know how to operate it. When I saw a function used as the second parameter of replace() in the source code today, I felt that it was difficult to read, so I planned to sort out this function...
Grammar
stringObject.replace(regexp/substr, replacement)
Return value
Returns a new string obtained by replacing the first match or any desired match of regexp with replacement
When the parameter replacement of the replace() method is a function, in this case, the function is called for each match, and the string returned by the function is used as the replacement text. The first parameter of this function is a string matching the pattern. The next parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The next parameter is an integer that declares the position in stringObject where the match occurs. The last parameter is the stringObject itself. This sentence was copied from w3cschool. For me now, I don’t quite understand the above paragraph, and I can’t simply describe it in my own words, so I can only use examples to illustrate it all
The above is the jquery source code I was looking at today
I feel like I understand this function now that I didn’t understand it at the time
Then now I remember that I don’t know when in the past, I encountered strange symbols when using replace(), which were strange symbols to me at that time, such as "$1, $2" and so on. Now Ye Lai has an answer to this question
$1, $2, $3.... means capturing 1, 2, 3....
$& represents a substring matching regexp
$` represents the text located to the left of the matching substring
$' represents the text located on the right side of the matched substring
$$ is directly the $ symbol
The above is where I am not clear about the use of the replace() method. I am a front-end novice. If there is something wrong in what I wrote, or if there are examples of better usage of this method, I hope you can share it...
The above is the entire content of this article, I hope you all like it.