Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 967
Timo Ernst Avatar asked Dec 15 '17 16:12

Timo Ernst


2 Answers

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()));
like image 63
ibrahim mahrir Avatar answered Sep 21 '22 08:09

ibrahim mahrir


Maybe you could use kebabCase from lodash: https://lodash.com/docs/4.17.15#kebabCase

like image 27
Luci Furtun Avatar answered Sep 21 '22 08:09

Luci Furtun