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

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值