本文详细讲解了在JavaScript中实现下划线命名与驼峰命名相互转换的多种方法。内容涵盖利用正则表达式、数组reduce方法以及map方法进行字符串处理的代码示例,适用于前后端参数格式不一致时的Key值转换场景。
应用场景:
在前后端交互中,有时后端接口返回的数据字段采用下划线命名规范,而前端接收或发送参数时习惯使用驼峰命名。此时,需要对对象的键名(Key)进行转换以适配不同的命名规范。
方法一:正则表达式(推荐)
将驼峰命名转换为下划线命名:
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_lin
JS字符串的下划线命名和驼峰命名转换
1. 将驼峰命名转换为连字符(中划线)命名:
var s = "fooStyleCss";
s = s.replace(/([A-Z])/g,"-$1").toLowerCase();
//利用正则进行替换,简洁明了,很棒
2. 将连字符命名转换为驼峰命名:
var s1 = "foo-style-css";
s1 = s1.replace(//-(/w)/g, function(all, letter){
return letter.toUpperCase();
});
//这段2看的不是很明白
以下是手动编写的实现方式,逻辑较为直观,但代码量相对较多:
var s = "style-sheet-base";
var a = s.split("-");
var o = a[0];
for(var i=1;i<a.length;i++){
o = o + a[i].slice(0,1).toUpperCase() + a[i].slice(1);
}
另一种使用正则表达式的实现方式:
var s1 = "style-sheet-base";
s1 = s1.replace(//-(/w)/g, function(x){return x.slice(1).toUpperCase();});
至此,关于JavaScript中下划线与驼峰命名相互转换的多种实现方法介绍完毕。如需了解更多相关内容,可查阅本站过往文章或继续浏览后续章节。