驼峰式转下横线:
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驼峰式转下横线:
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驼峰式转下横线:
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
