javascriptarraysstringcamelcasingkebab-case

Convert kebab-case to camelCase with JavaScript


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");

Solution

  • 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.