gpt4 book ai didi

javascript - 如何从驼峰式大小写转换为虚线和虚线转换为驼峰式大小写

转载 作者:行者123 更新时间:2023-11-30 07:53:08 24 4
gpt4 key购买 nike

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

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

关于javascript - 如何从驼峰式大小写转换为虚线和虚线转换为驼峰式大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com