Copy codeThe Code is as follows:
// Convert word-word to wordWord
Function camelize (s ){
Return s. replace (/-(\ w)/g, function (strMatch, p1 ){
Return p1.toUpperCas ();
});
}
Here we have applied the replace function, which is familiar to everyone. Now we will introduce the situation when his second parameter is a function.
When I sent this function in the group today, some people reported that the above regular expression was incorrect./-(\ W)/G ", and then I quickly understood that his doubt is this" () ". In fact, this bracket is necessary:
(X) matches x and saves x in the variable $1, $2... $9. In fact, it adds an index to it to facilitate subsequent calls. If this bracket is not added, an error occurs:
Okay. The following describes the meaning of function parameters. Why can this function implement the specified function?
ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself.
It seems a little annoying. For example:
Copy codeThe Code is as follows:
Camelize (www-rrr );
That is to call it. In fact, the strMatch value above is-r, which is the string that matches the regular expression (The first parameter of this function is a matching string.),
The value of p1 above is r, which refers to the r (The following parameters are strings that match the subexpression in the pattern.), Which is the index we specify --"(\ W)".
Well, I think we can see exactly what this function will execute,Additional proposals are welcome.
S. replace (/-([a-z])/ig, function (all, letter) {return letter. toUpperCase () ;}); \ w also includes numbers and _
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]