方法一:正则表达式 (推荐)
function underlineToHump(str) {
if(str.slice(0,1) === '_'){
str = str.slice(1);
}
return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
return $1 + $2.toUpperCase();
});
}
function humpToUnderline(str) {
let temp = str.replace(/[A-Z]/g, function (match) {
return "_" + match.toLowerCase();
});
if(temp.slice(0,1) === '_'){
temp = temp.slice(1);
}
return temp;
}
console.log(underlineToHump('a_b2_23_c23'),underlineToHump('_test_to_lower_line'));
console.log(humpToUnderline('userNameInfo'),humpToUnderline('TestToLowerLine'));
方法二:利用数组的 reduce 方法实现
function doCamel(preVal, curVal, curIndex, arr){
if(curVal === '_'){
curVal = arr[curIndex + 1];
arr.splice(curIndex + 1, 1)
return preVal + curVal.toUpperCase();
}else{
return preVal + curVal;
}
}
function underlineToHump(str) {
if(typeof str === 'string' && str.length){
str = str.split('');
const fir = str.slice(0,1)[0];
if(fir === '_'){
str = str.slice(1);
}
return str.reduce(doCamel);
}
}
function doUnderline(preVal, curVal, curIndex, array){
if(/[A-Z]/.test(curVal)){
curVal = curVal.toLowerCase();
if(curIndex === 0){
return preVal + curVal;
}else{
return preVal + '_' + curVal;
}
}else{
return preVal + curVal;
}
}
function humpToUnderline(str) {
if(typeof str === 'string'){
str = str.split('');
}
return str.reduce(doUnderline,'');
}
console.log(underlineToHump('a_b2_23_c23'),underlineToHump('_test_to_lower_line'));
console.log(humpToUnderline('userNameInfo'),humpToUnderline('TestToLowerLine'));
方法三:利用数组的 map 方法实现
function doHump(val,index,arr){
if(val === '_'){
val = arr[index + 1];
arr.splice(index + 1, 1)
return val.toUpperCase();
}else{
return val;
}
}
function underlineToHump(str) {
if(typeof str === 'string' && str.length){
str = str.split('');
const fir = str.slice(0,1)[0];
if(fir === '_'){
str = str.slice(1);
}
return [].map.call(str,doHump).join('');
}
}
function doUnderline(val,index,arr){
if(/[A-Z]/.test(val)){
if(index === 0){
return val.toLowerCase();
}else{
return '_' + val.toLowerCase();
}
}else{
return val;
}
}
function humpToUnderline(str) {
if(typeof str === 'string'){
return [].map.call(str,doUnderline).join('');
}
}
console.log(underlineToHump('a_b2_23_c23'),underlineToHump('_test_to_lower_line'));
console.log(humpToUnderline('userNameInfo'),humpToUnderline('TestToLowerLine'));