我如何从驼峰案例转换为虚线和虚线到驼峰案例

Int*_*lia 1 javascript

1)你如何转换骆驼案例字符串像"backgroundColor"虚拟案例和"background-color"

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

Int*_*lia 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'));
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)