How to convert a camel-case string to dashes in JavaScript?

Timo Ernst picture Timo Ernst · Dec 15, 2017 · Viewed 8.8k times · Source

I want to convert these strings:

fooBar
FooBar

into:

foo-bar
-foo-bar

How would I do this in JavaScript the most elegant and performant way for any given string?

Answer

ibrahim mahrir picture ibrahim mahrir · Dec 15, 2017

You can use replace with a regex like:

let dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());

which matches all uppercased letters and replace them with their lowercased versions preceded by "-".

Example:

console.log("fooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));