这篇文章主要介绍js如何实现下划线和驼峰互相转换,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
有时候传给后端的参数是驼峰命名,回显的时候是下划线,这个时候就需要修改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
驼峰式转下横线:
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_lin
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如何实现下划线和驼峰互相转换”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。