DEV Community

Discussion on: JavaScript Challenge 6: Convert string to camel case

Collapse
 
zerodragon profile image
Zero Dragon

Since split already uses g as regex mod... and there is no need to use i when you are not looking for [a-z|A-Z] chars...

const toCamelCase = string => {
  const [head, ...tail] = string.split(/-|_/)
    .map(([head, ...tail]) => 
      [
        head.toUpperCase(),
        tail.join('').toLowerCase()
      ].join(''))
    .join('')
  return [head.toLowerCase(), ...tail].join('')
}

console.log(toCamelCase('THE_awesome-and_sUPERB-stealth-WARRIOR'))
//theAwesomeAndSuperbStealthWarrior
Enter fullscreen mode Exit fullscreen mode

Also added some valiations to fix improper output camelCase casing

Collapse
 
albertomontalesi profile image
AlbertoM

Awesome, one thing. Your output theAwesomeAndSuperbStealthWarrior should have the first letter be capitalized since it was like that in the original string.

See the challenge requirement:

"The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case)."

Collapse
 
zerodragon profile image
Zero Dragon

You are correct! here is the revisited version:

const toCamelCase = ([first, ...rest]) => {
  const [head, ...tail] = rest.join('').split(/-|_/)
    .map(([head, ...tail]) => 
      [
        head.toUpperCase(),
        tail.join('').toLowerCase()
      ].join(''))
    .join('')
  return [first, head.toLowerCase(), ...tail].join('')
}

console.log(toCamelCase('THE_awesome-and_sUPERB-stealth-WARRIOR'))
console.log(toCamelCase('tHE_awesome-and_sUPERB-stealth-WARRIOR'))

// TheAwesomeAndSuperbStealthWarrior
// theAwesomeAndSuperbStealthWarrior
Enter fullscreen mode Exit fullscreen mode

darn PascalCase...