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?
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()));
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
FooBar
converted to -foo-bar
instead of foo-bar
–
Fancy 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'))
`
$&
. –
Laurettalaurette You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.
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()}`)
-${g[0].toLowerCase()}
) –
Dipetalous 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`))
If you want a simple way to do that, you can use CaseParser to do that.
All you need to do is install the package to your project:
npm add caseparser
And then, use it like the following example. If you pass a string 'fooBar', you could convert it into many 'cases':
// import using ESM
import caseparser from 'caseparser';
// or using CommonJS
const caseparser = require('caseparser');
// Using CaseParser library
caseparser.camelToDash('fooBar'); // 'foo-bar'
caseparser.camelToPascal('fooBar'); // 'FooBar'
caseparser.camelToSnake('fooBar'); // 'foo_bar'
caseparser.camelToUpperDash('fooBar'); // 'FOO-BAR'
caseparser.camelToUpperSnake('fooBar'); // 'FOO_BAR'
It converts json object's keys and arrays too. For the latest versions (2.x.x) now supports typesafe after the conversion!
I hope to help you :)
© 2022 - 2024 — McMap. All rights reserved.