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?
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()));
Maybe you could use kebabCase
from lodash: https://lodash.com/docs/4.17.15#kebabCase
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With