Coding Challenge - #27: Convert Case Style

Write a function toCamelCase(str) that converts a kebab-case or snake_case string into camelCase. For example, toCamelCase('font-size') and toCamelCase('font_size') should both return 'fontSize', while toCamelCase('background_color_name') should return 'backgroundColorName'.

function toCamelCase(str) {
  // Your code here
}

Rules:

  • Must handle both hyphens (-) and underscores (_) as delimiters
  • Do not capitalize the first character of the string
  • Return the converted string

Post your solution as a reply. Answer goes up in about a day.

Hmm, the challenge seems straightforward. But what happens if a key already has a camelCase segment in it? Like some-CSSProperty? Does it become someCssProperty or someCSSProperty? The rules don’t specify.

That’s a good question. Usually, these converters treat the whole string as a sequence of words, so it would likely end up as someCssProperty.

You might want to check if your regex handles existing caps by splitting them before the conversion logic kicks in. Otherwise, you end up with weird stuff.

You’re right, handling existing caps is a good point. If you need to deal with a string like someCSSProperty and convert it to someCssProperty, you might need a more advanced regex.

Here’s a tutorial that goes into more detail on how to handle different string cases, including some of those edge cases: https://www.kirupa.com/html5/case_styles.htm

Challenge solution: The challenge requires converting kebab-case or snake_case strings to camelCase by removing delimiters and capitalizing the letter following them, while ensuring the first character remains lowercase.

One way to do it:

function toCamelCase(str) {
  return str.replace(/[-_](.)/g, (match, char) => char.toUpperCase());
}

Why:
This solution uses a regular expression /-_/g to find all occurrences of either a hyphen or an underscore followed by any character. The ‘g’ flag ensures all matches are replaced. For each match, the callback function receives the full match (e.g., ‘-s’) and the captured character (e.g., ‘s’). It then returns the captured character converted to uppercase, effectively removing the delimiter and capitalizing the subsequent letter.

First-answer leaderboard

  1. @emmawalter5 - 8 (firsts) :trophy:
  2. @kirupa - 8 (firsts) :trophy:
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

That regex is super clean, I love how it handles both cases in one go. definitely the most efficient way to do it.