Intervalia
Intervalia

Reputation: 10965

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

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

Upvotes: 2

Views: 1334

Answers (1)

Intervalia
Intervalia

Reputation: 10965

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

And, in 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'));

Upvotes: 6

Related Questions