28

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?

Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
  • 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. – Danmoreng Dec 15 '17 at 16:34
  • 1
    @Danmoreng Wouldn't a regex be better? – Timo Ernst Dec 15 '17 at 16:35
  • Sure you could also use a regex with [String.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) – Danmoreng Dec 15 '17 at 16:37
  • i guess the most elegant- would most likely not the most performant-solution – snap Dec 15 '17 at 16:39

8 Answers8

55

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()));
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
15

For those who do not need the preceding hyphen:

console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))
ceving
  • 21,900
  • 13
  • 104
  • 178
12

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

Luci Furtun
  • 169
  • 1
  • 5
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'))

`

Shalitha Suranga
  • 1,138
  • 8
  • 24
2

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

jkordas
  • 155
  • 6
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()}`)
Community
  • 1
  • 1
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`))
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 :)

NandoMB
  • 151
  • 1
  • 9