Medium

snakeToCamel

Prompt

Write a function snakeToCamel that converts a string from snake_case to camelCase.

Playground

Hint 1

You need to detect underscores and capitalize the character that comes right after them. A boolean flag that says "make the next character uppercase" is one approach.

Hint 2

Alternatively, you can split('_') the string into an array of words, capitalize the first letter of each word (except the first one), and join('') them back together.

Solution

Explanation

We walk through the string character by character with a flag called capitalizeNext. When we hit an underscore, we don't add it to the result. Instead, we set capitalizeNext = true. The next character we encounter gets uppercased, and we reset the flag.

if (str[i] === '_') {
capitalizeNext = true;
} else {
result += capitalizeNext ? str[i].toUpperCase() : str[i];
capitalizeNext = false;
}

For 'hello_world':

  • h, e, l, l, o get added as-is
  • _ is skipped, capitalizeNext becomes true
  • w gets uppercased to W, capitalizeNext resets to false
  • o, r, l, d get added as-is
  • Result: "helloWorld"

The underscore acts as a signal: "capitalize whatever comes next." We consume the signal and throw away the underscore.

Alternative: split and join

You can also solve this by splitting on underscores:

function snakeToCamel(str) {
return str
.split('_')
.map((word, i) =>
i === 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join('');
}

split('_') turns 'hello_world' into ['hello', 'world']. Then we capitalize the first letter of every word except the first one, and join them back together. Both approaches are valid. The flag approach is more "algorithmic," the split approach is more "JavaScript-y."

When do you need this?

API responses often come in snake_case (especially from Python/Ruby backends), but JavaScript convention is camelCase. Converting between them is a real-world task you'll encounter when working with APIs.