应用场景:
有时候传给后端的参数是驼峰命名,回显的时候是下划线,这个时候就需要修改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_lineconsole.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_linevar 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_linevar 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();}); 到此这篇关于js下划线和驼峰互相转换的实现(多种方法)的文章就介绍到这了,更多相关js下划线和驼峰互相转换内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net! 下载地址: elementUI实现下拉选项加多选框的示例代码 JavaScript中判断的优雅写法示例 |