1.用传统的字符串操作,要把-b和-c转成大写的B和C。那么我们可以用split()方法来进行分割利用toUpperCase()方法来转大写。最后用join()方法来拼接。
1 foo="get-element-by-id"; 2 function test(str){ 3 var arr=str.split('-'); 4 for(var i=1;i<arr.length;i++){ 5 arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substring(1); 6 } 7 var result=arr.join(''); 8 return result; 9 } 10 console.log(test(foo));
2.用正则表达式的方法。
1 var str = "border-bottom-color"; 2 function test(str){ 3 var re = /-(w)/g;//通过正则找到-b -c。默认的是匹配一次,所以要用g来全局匹配。w指的字符。找一个-找一个字符。replace替换就是B替换-b C替换-c。 $0代表str中与re匹配的字符串,$1代表指向第一个分组的匹配的字符串 4 return str.replace(re, function($0,$1){ 5 return $1.toUpperCase(); 6 }); 7 } 8 console.log(test(str));