I want to convert these strings:
fooBar
FooBar
into:
foo-bar
-foo-bar
How would I do this in JavaScript the m
Simple case:
"fooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
"FooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
Edge case: this can get an extreme case where you have a single char.
"FooBarAFooBar".replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)
For those who do not need the preceding hyphen:
console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))
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()));
You can use
const makeItDashed = camelCased => {
let dashed = ``
camelCased.split(``).map(ch => {{dashed += ch.toUpperCase() == ch ? `-${ch.toLowerCase()}` : ch}})
return dashed
}
console.log(makeItDashed(`fooBar`))
console.log(makeItDashed(`FooBar`))
You can use replace()
with regex. Then use toLowerCase()
let camel = (s) => s.replace(/[A-Z]/g, '-$&').toLowerCase()
console.log(camel('fooBar'))
console.log(camel('FooBar'))
`
You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.