简体   繁体   English

我如何从骆驼案转换为破折号和破折号为骆驼案

[英]How do I convert from camel case to dashed and dashed to camel case

1) How do you convert a camel case string like "backgroundColor" to dashed case like "background-color" and 1)如何将驼峰大小写字符串(例如"backgroundColor" )转换为虚线大小写(例如"background-color"

2) How do you convert dashed case "background-color" to camel case "backgroundColor" 2)如何将虚线大小写的"background-color"转换为骆驼的大小写"backgroundColor"

Here are the two functions I use: 这是我使用的两个功能:

 function camelToDash(str){ return str.replace(/([AZ])/g, function($1){return "-"+$1.toLowerCase();}); } function dashToCamel(str){ return str.replace(/(\\-[az])/g, function($1){return $1.toUpperCase().replace('-','');}); } console.log('camelToDash ->', camelToDash('camelToDash')); console.log('dash-to-camel ->', dashToCamel('dash-to-camel')); 

And, in ES6: 并且,在ES6中:

 const camelToDash = str => str.replace(/([AZ])/g, val => `-${val.toLowerCase()}`); const dashToCamel = str => str.replace(/(\\-[az])/g, val => val.toUpperCase().replace('-','')); console.log('camelToDash ->', camelToDash('camelToDash')); console.log('dash-to-camel ->', dashToCamel('dash-to-camel')); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM