DEV Community

Cover image for JavaScript Challenge 6: Convert string to camel case
AlbertoM
AlbertoM

Posted on • Originally published at inspiredwebdev.com

JavaScript Challenge 6: Convert string to camel case

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials. Check out my JavaScript course on Educative to learn everything from ES6 to ES2020.

 

In this article we will solve together the Convert string to camel case challenge from CodeWars, you can find it at this link. The difficulty of this challenge is easy.

Let's read the task together:

Complete the method/function so that it converts dash/underscore delimited words into camel casing. 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).

Examples
toCamelCase("the-stealth-warrior") // returns >"theStealthWarrior"

toCamelCase("The_Stealth_Warrior") // returns "TheStealthWarrior"

The easiest way to solve this challenge will be with RegEx and we don't even need a complicate one in this case:

 

Write the RegExp

/[-_]\w/ig this is all we need.

  • [-_] will match all the underscore and dashes
  • \w will match any character right after a dash or underscore
  • /ig will perform a global case insesitive search.

The trick that will help us complete the challenge more easily is the \w which allows us to capture the letter right after a dash or underscore, meaning we can easily make it uppercase in one go.

When you want to play around with RegEx, this is a great playground that also explains how they work regexr.com.

Now that we have the most important piece of our function, let's try and build a function around it.

function toCamelCase(str){
      const regExp = /[-_]\w/ig;
      return str.replace(regExp,(match) => {
          console.log(match);
       });
}
toCamelCase("the-stealth-warrior")
// -s
// -w
Enter fullscreen mode Exit fullscreen mode

String.replace() can take not only a substring but only a RegExp as the first parameter and will pass the result in the second one.

As you can see our RexExp matched each dash and the first character after.

Completing the function

Now what we are left to do with the function is to return only the uppercase letter without the dash or underscore.

function toCamelCase(str){
      const regExp = /[-_]\w/ig;
      return str.replace(regExp,(match) => {
          return match[1].toUppercase()
       });
}
toCamelCase("the-stealth-warrior")
Enter fullscreen mode Exit fullscreen mode

That's it, the last line we added will return S instead of -s and W instead of -w.

here are many other ways of solving this problem, let me know yours in the comment.

If you liked this type of content, please let me know in the comments and I'll create more of these.


If you want to learn everything about JavaScript from ES6 all the way to ES2020, please check out my book available to read for free on Github. A course is also on Educative

Alt Text

 

Top comments (4)

Collapse
 
gdaz profile image
Sathaphorn Phansiri • Edited

This is my idea

var result = "string_poem-pATH".split(/-|_/)
.map((e, i, arr) => {
  return i == 0 ? e.toLowerCase() : e.toLowerCase().replace(arr[i].charAt(0), arr[i].charAt(0).toUpperCase());
}).join("");

console.log(result);
Enter fullscreen mode Exit fullscreen mode
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...