admin 管理员组

文章数量: 1087582

JS 实现:驼峰式转下横线,下横线转驼峰式

方法一:正则表达式 (推荐)

驼峰式转下横线:

function toLowerLine(str) {var temp = str.replace(/[A-Z]/g, function (match) {	return "_" + match.toLowerCase();});if(temp.slice(0,1) === '_'){ //如果首字母是大写,执行replace时会多一个_,这里需要去掉temp = temp.slice(1);}return temp;
};
console.log(toLowerLine("TestToLowerLine"));  //test_to_lower_line
console.log(toLowerLine("testToLowerLine"));  //test_to_lower_line

下横线转驼峰式:

function toCamel(str) {return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {return $1 + $2.toUpperCase();});
}
console.log(toCamel('test_to_camel')); //testToCamel

方法二:利用数组的 reduce 方法实现

驼峰式转下横线:

function doLowerLine(previousValue, currentValue, currentIndex, array){if(/[A-Z]/.test(currentValue)){currentValue = currentValue.toLowerCase();if(currentIndex===0){return previousValue + currentValue;}else{return previousValue + '_' + currentValue;}}else{return previousValue + currentValue;}
}
function toLowerLine(arr){if(typeof arr === 'string'){arr = arr.split('');}return arr.reduce(doLowerLine,'');
}
var a = 'TestToLowerLine';
var res1 = toLowerLine(a);	//test_to_lower_line
var res2 = [].reduce.call(a,doLowerLine,'');	//test_to_lower_line

下横线转驼峰式:

function doCamel(previousValue, currentValue, currentIndex, array){if(currentValue === '_'){return previousValue + currentValue.toUpperCase();}else{return previousValue + currentValue;}
}
function toCamel(str) {if(typeof str === 'string'){str = str.split(''); //转为字符数组}return str.reduce(doCamel);
}
console.log(toCamel('test_to_camel'));    //TestToCamel

方法三:利用数组的 map 方法实现

驼峰式转下横线:

function doLowerLine(val, index, arr){if(/[A-Z]/.test(val)){if(index===0){return val.toLowerCase();}else{return '_'+val.toLowerCase();}}else{return val;}
}
function toLowerLine(arr){if(typeof arr === 'string'){return [].map.call(arr,doLowerLine).join('');// Array.prototype.map.call(arr, doLowerLine).join('');}else{return arr.map(doLowerLine).join('');}
}
var a = 'TestToLowerLine';
var res1 = [].map.call(a,doLowerLine).join('');    //test_to_lower_line
var res2 = toLowerLine(a);    //test_to_lower_line

 

本文标签: JS 实现驼峰式转下横线,下横线转驼峰式