DEV Community

Justin
Justin

Posted on • Edited 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.

Dynatrace image

Highlights from KubeCon Europe 2025

From platform engineering to groundbreaking advancements in security and AI, discover the KubeCon Europe 2025 insights that are shaping the future of cloud native observability.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo