Function
The function of the camelCase function is to convert the form of background-color to the camelCase Notation: backgroundColor.
This function is useful in jQuery data functions and many functions related to css.
JQuery implementationCopy codeThe Code is as follows: // Regular Expression matching
RdashAlpha =/-([a-z])/ig,
// Callback function when camelCase replaces the string
FcamelCase = function (all, letter ){
Return letter. toUpperCase ();
},
...
CamelCase: function (string ){
Return string. replace (rdashAlpha, fcamelCase );
},
This function is not difficult. It calls the replace method of the String object. However, I studied the replace method with a learning attitude.
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
String. replace () syntax
Str. replace (regexp | substr, newSubStr | function [, Non-standard flags]);
String. replace () parameter description
Regexp: a regular expression used for searching
Substr: a search string
NewSubStr: A New string to be replaced.
Function: a callback function. The return value of the function is used to replace the original matched string.
Flags: non-standard, similar to I, g, and m of RegExp (case-insensitive, global search or multi-row matching)
Specify a string as a replacement object
In the string to be replaced, you can use the following mode:
$ => Insert a $
$ & => Insert matched substrings
$ '=> Insert all characters before the matched substring
$ '=> Insert all characters after the matched substring
$ N/$ nn => This mode is valid only when the first parameter of the replace () method is RegExp and the regular expression contains parentheses.
Specify the function as the replacement object
Typical replacement functions: function (str, p1, p2, offset, s ){}
Parameter description:
Str: matched string (similar to $ &)
P1, p2,...: This mode is valid only when the first parameter of the replace () method is RegExp and the regular expression contains parentheses. (Similar to $ n/$ nn)
Offset: the offset that matches the substring.
S: string used for search
Get the camper representation of the CSS attribute Copy codeThe Code is as follows: String. prototype. camelCase = function (){
// All is the matched substring, and letter is p1, because [a-z] is added with parentheses
Return this. replace (/-([a-z])/ig, function (all, letter, offset, s ){
Return letter. toUpperCase ();
});
};
Var cssText = 'h2 \ n {\ n border-bottom: 1px solid # eee; \ n background-color: # bbb; \ n }';
Var newstr = cssText. camelCase ();
Returns the position of the string to be matched. Copy codeThe Code is as follows: var re =/(\ w +) \ s (\ w + )/;
Var str = "John Smith ";
Var newstr = str. replace (re, "$2, $1 ");