我如何从驼峰转换为虚线和虚线转换为驼峰的情况

时间:2017-12-21 21:19:00

标签: javascript

1)如何将像"backgroundColor"这样的驼峰案例字符串转换为"background-color"

等虚拟案例

2)如何将虚线案例"background-color"转换为驼峰案"backgroundColor"

1 个答案:

答案 0 :(得分:6)

以下是我使用的两个功能:



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'));




而且,在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'));