DEV Community

Justin
Justin

Posted on • Updated on

JS Challenge: Convert snake_case to camelCase

I have seen many JavaScript snippets to convert strings in snake case to camel case. For example the following string:

SNAKE_casE

will look like this after conversion:

snakeCase

One snippet I have seen recently in a forum goes like this:

let str = 'SNAKE_casE';
const [firstPart, lastPart] = str.toLowerCase().trim().split("_");
const outputCamelCase = `${firstPart}${lastPart.replace(
  lastPart[0],
  lastPart[0].toUpperCase()
)}`;
console.log(outputCamelCase);
Enter fullscreen mode Exit fullscreen mode

which will produce an output:

snakeCase

But what if the snake case string has multiple segments as below:

SNAKE_casE___WITH_muLtiPLE_SEGments

The code above can deal with only two segments.

Here is my take on the problem. This one-liner should work for any snake case string even those with multiple segments:

let str = 'SNAKE_casE___WITH_muLtiPLE_SEGments';
str.toLowerCase().replace(/_+(.)/g, (m, g) => 
  {return g.toUpperCase()}
);
Enter fullscreen mode Exit fullscreen mode

First it converts the entire string to lower case. Then scans the string for occurrences of underscore(s) followed by a single character (.) and globally replaces those occurrences with the upper case of the character that follows the underscore(s). Notice the second argument in the call to replace() is a function - in this case it returns the character converted to upper case. If the second argument to replace() is a function it can take the match and the capture groups as arguments and return a value to replace the match. See the reference for a complete description.

Top comments (0)