本文介绍了我如何从驼峰转换为虚线和虚线转换为驼峰的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)如何将像backgroundColor这样的驼峰案例字符串转换为虚拟大小写,如background-color

1) How do you convert a camel case string like "backgroundColor" to dashed case like "background-color" and

2)如何将虚线大小写background-color转换为驼峰大小写backgroundColor

2) How do you convert dashed case "background-color" to camel case "backgroundColor"

推荐答案

以下是我使用的两个函数:

Here are the two functions I use:

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

这篇关于我如何从驼峰转换为虚线和虚线转换为驼峰的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:12