Convert kebab-case to camelCase with JavaScript
Asked Answered
T

5

37

Say I have a function that transforms kebab-case to camelCase:

camelize("my-kebab-string") === 'myKebabString';

I'm almost there, but my code outputs the first letter with uppercase too:

function camelize(str){
  let arr = str.split('-');
  let capital = arr.map(item=> item.charAt(0).toUpperCase() + item.slice(1).toLowerCase());
  let capitalString = capital.join("");

  console.log(capitalString);
}
    
camelize("my-kebab-string");
Tarshatarshish answered 19/8, 2019 at 12:11 Comment(1)
arr.map((item, index)) => if (index > 0) { ... } else { ... })Cyanosis
P
87

You can also try regex.

camelize = s => s.replace(/-./g, x=>x[1].toUpperCase())

const camelize = s => s.replace(/-./g, x=>x[1].toUpperCase())
const words = ["stack-overflow","camel-case","alllowercase","allcapitalletters","custom-xml-parser","api-finder","json-response-data","person20-address","user-api20-endpoint"];
console.log(words.map(camelize));

Looks only for hyphen followed by any character, and capitalises it and replaces the hyphen+character with the capitalised character.

Portwine answered 18/3, 2020 at 11:48 Comment(1)
Genius, but I would go with x=>x[1].toUpperCase()Septate
U
14

To keep your existing code, I've just added a check on the index that will return item instead of the transformed item if item is 0 (falsy), since the problem is just that you are upper-casing the first item as well, while you shouldn't.

In a nutshell, the inline expression becomes: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item, because:

  • If index is not falsy (so, if index is > 0 in your context), the capitalized string is returned.
  • Otherwise, the current item is returned.

Of course, this could be cleaner and likely single line, but I wanted to stay as close as possible to your code so that you could understand what was wrong:

function camelize(str){
  let arr = str.split('-');
  let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item.toLowerCase());
  // ^-- change here.
  let capitalString = capital.join("");

  console.log(capitalString);
}

camelize("my-kebab-string");

As a side note, you could've found a potential cleaner answer here: Converting any string into camel case

Ure answered 19/8, 2019 at 12:16 Comment(2)
I knew that I can use the index attribute for this case, but don't wonder how currently. Thank You very much!Tarshatarshish
@RobertHovhannisyan well, the index is just one of the possible solutions out there. For performance reasons, you may want to check the linked topic, this can easily be accomplished with a single regex instead of mapping :).Ure
S
6

For lodash users:

_.camelCase('my-kebab-string') => 'myKebabString'
Sapowith answered 28/6, 2020 at 15:50 Comment(0)
Z
2

The first method is to just transform to lower case the first entry of your capital array, like this:

capital[0] = capital[0].toLowerCase();

Another method, which I think to be more efficient, is to pass another parameter to the map callback, which is the index. Take a look at this for further reading: https://www.w3schools.com/jsref/jsref_map.asp

So you transform to upper case only if (index > 0). Like this:

let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item);
Zirconia answered 19/8, 2019 at 12:14 Comment(0)
U
0

so I tried both array-string and regex but regex is slower !

const string = " background-color: red; \n color: red;\n z-index: 10"

// regex
console.time("regex")
let property = string
const camelProp = property.replace(/(-[a-z])/, (g) => {
  return g.replace("-", "").toUpperCase()
})
console.timeEnd("regex")

// custom
console.time("custom")
const str = string
let strNew = str
  .split("-")
  .map((e) => {
    return e[0].toUpperCase() + e.slice(1)
  })
  .join("")

console.timeEnd("custom")

console.log(camelProp)
console.log(strNew)
Uncurl answered 25/5, 2022 at 5:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.