How to convert a camel-case string to dashes in JavaScript?
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()));
For those who do not need the preceding hyphen:
console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))
Maybe you could use kebabCase
from lodash: https://lodash.com/docs/4.17.15#kebabCase