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

8

31

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?

Unthinking answered 15/12, 2017 at 16:32 Comment(4)
Split into an array of characters, check for uppercase characters, replace them by their lowercase pendent + the dash in front, combine the array back to a string.Saleh
@Saleh Wouldn't a regex be better?Unthinking
Sure you could also use a regex with String.replaceSaleh
i guess the most elegant- would most likely not the most performant-solutionProstatitis
L
59

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()));
Laurettalaurette answered 15/12, 2017 at 16:38 Comment(0)
B
16

For those who do not need the preceding hyphen:

console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))
Baudelaire answered 23/12, 2020 at 19:6 Comment(0)
G
12

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

Gratuitous answered 13/1, 2020 at 22:8 Comment(1)
If @timo-ernst trying to use dataset, the problem is FooBar converted to -foo-bar instead of foo-barFancy
E
4

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'))

`

Echovirus answered 15/12, 2017 at 16:43 Comment(2)
One note: you don't need to group the match. Just remove the parens and use $&.Laurettalaurette
@ibrahimmahrir It's nice but there is warning notice in documentationEchovirus
C
2

You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.

Callimachus answered 15/12, 2017 at 16:38 Comment(1)
I like the "Don't reinvent the wheel approach"Unthinking
D
0

EDIT

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()}`)
Dipetalous answered 15/12, 2017 at 16:38 Comment(3)
OP wants to include the first letter too.Laurettalaurette
hi @ibrahimmahrir thanks to let me notice that, this should fix his problem and also consider the edge case where he has a single char in capital letter. "FooBarAFooBar".replace(/([A-Z])/g, (g) => -${g[0].toLowerCase()})Dipetalous
Unnecessarily complicated regex pattern, that's why you need to separately handle single uppercaseUntraveled
J
0

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`))
Jaret answered 15/12, 2017 at 16:48 Comment(0)
F
0

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 :)

Fatty answered 24/4, 2023 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.