1)你如何转换骆驼案例字符串像"backgroundColor"虚拟案例和"background-color"和
2)如何将虚拟案例转换"background-color"为驼峰案例"backgroundColor"
以下是我使用的两个函数:
function camelToDash(str){
return str.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();});
}
function dashToCamel(str){
return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
}
console.log('camelToDash ->', camelToDash('camelToDash'));
console.log('dash-to-camel ->', dashToCamel('dash-to-camel'));Run Code Online (Sandbox Code Playgroud)
而且,在ES6中:
const camelToDash = str => str.replace(/([A-Z])/g, val => `-${val.toLowerCase()}`);
const dashToCamel = str => str.replace(/(\-[a-z])/g, val => val.toUpperCase().replace('-',''));
console.log('camelToDash ->', camelToDash('camelToDash'));
console.log('dash-to-camel ->', dashToCamel('dash-to-camel'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |