在js中,驼峰命名一般首字母小写,其它首字母大写的形式。短横线命名所有字母小写,单词与单词之间用短横线连接。
搞清楚区别之后就很简单了,使用正则全局匹配大写字母并替换成短横线+小写字母,或者匹配短横线+小写字母替换成大写字母。
replace的具体用法参考MDNString.prototype.replace
// 驼峰转短横线
let str = "testStrName";
let newStr = str.replace(/([A-Z])/g, (match, p1, offset, string) => {
// 一个捕获组捕获全部,所以match等于p1
return '-' + p1.toLowerCase();
});
console.log(newStr);
// 短横线转驼峰
let newStr2 = newStr.replace(/(\-([a-z]))/g, (match, p1, p2, offset, string) => {
// 这里有两个捕获组,第一个捕获组捕获全部并包含了第二个捕获组,所以match等于p1
return p2.toUpperCase();
});
console.log(newStr2);