- 1、用普通的方法
function transformStr ( str ) {
if(str == '') {
throw new Error('不符合规范')
}
var arr = str.split('-');//split是分隔字符串
var newStr = arr[0];
for(var i = 1; i<arr.length; i++){
newStr += (arr[i].substr(0,1).toLocaleUpperCase() +arr[i].slice(1));
}
return newStr;
}
//测试案例
var stringTuoFeng='get-element-by-id';
console.log ( transformStr ( stringTuoFeng ) );
- 2 用正则的方法
var str="border-bottom-color";
function tf(){
var re=/-(\w)/g;
str=str.replace(re,function($0,$1){
// $0表示带符号的 $1表示不带符号的
return $1.toUpperCase();
});
return str
};
tf(str);