Topic description
There are often characters connected by - such as background-image in css. When setting the style through javascript, you need to convert this style into backgroundImage camel case format. Please complete this conversion function
1. Use - as the separator, put the second The first letter of a non-empty word starting from 2 is uppercase
2. -webkit-border-image The converted result is webkitBorderImage
1 //第一种方法
2 function cssStyle2DomStyle(sName) {
3 var str = sName.split("-");
4 //console.log(str);
5 var result = "";
6 var one = "";
7 var i;
8 if(str[0] == ""){
9 for( i =2 ; i<str.length ; i++){
10 one = "";
11 one += str[i].charAt(0);
12 result += (one.toLocaleUpperCase()+str[i].slice(1));//slice(index): Take the character at index position until the end
13 // console.log(result);
14 }
15 result = str[1] + result;
16 }
17 else {
18 for ( i =1 ; i<str. length ; i++ ){
19 one = "" ;
20 one += str[i].charAt(0 );
21 result += (one.toLocaleUpperCase()+str[i].slice(1)); // slice (index): Take the character at index position until the end
22 }
23 result = str[0] + result;
24 }
25 return result;
26 }
27 // The second method (refer to other people's code)
28 function cssStyle2DomStyle(sName) {
29 /*
30 (?!^) : backreference, meaning except the beginning of the string
31 \- : \ is an escape character, contains - character
32 (\w): contains one alphabetic character
33 (\w): contains one or more alphabetic characters
34 ^\-: ^ is the leading character, a string starting with
-35 * /
36 return sName.replace(/(?!^)\-(\w)(\w+)/g , function (a,b,c){
37 return b.toUpperCase() + c.toLowerCase();
38 }).replace(/^\-/,'' );
39}
Source: Niuke.com