CopyCode The 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 code The 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.
<textarea id="runcode49627"><Br/> S. replace (/-([A-Z])/ig, function (all, letter) {return letter. touppercase () ;}); <br/> \ W also includes numbers and _ <br/></textarea>
[Ctrl + A select all Note: If you need to introduce external JS, You need to refresh it to execute]