Write a function kebabToCamel(str) that converts a kebab-case string into camelCase. For example, kebabToCamel('font-size-adjust') should return 'fontSizeAdjust' and kebabToCamel('display') should return 'display'.
function kebabToCamel(str) {
// Your code here
}
Rules:
Assume all input characters are lowercase letters and hyphens.
Do not use external libraries.
Preserve strings with no hyphens as-is.
Post your solution as a reply. Answer goes up in about a day.
okay so we’ve got a first entry on the board! love seeing the different approaches people take to these kinds of string transforms. the solution drops later today!
Challenge solution: The task is to convert kebab-case strings to camelCase, which involves finding hyphens and capitalizing the character immediately following them.
One way to do it:
function kebabToCamel(str) {
return str.replace(/-([a-z])/g, (match, char) => char.toUpperCase());
}
Why:
This solution uses the replace() method with a regular expression. The regex /-([a-z])/g matches a hyphen followed by any lowercase letter globally. The matched letter is captured in a group. The replacement function then takes this captured letter and converts it to uppercase, effectively removing the hyphen and capitalizing the subsequent character.
That split and map approach works fine. It’s a clear way to handle the word-by-word transformation. The replace with regex is usually a bit faster for this kind of string work. Less overhead than splitting and rejoining.
function kebabToCamel(str) {
return str.replace(/-(\w)/g, (_, c) => c.toUpperCase());
}
Not that it matters much for short strings. Either way gets the job done.
Look. Concise regex is great until someone needs to debug it at 3am. I’ve seen some absolute nightmares come out of trying to be too clever with lookbehinds.
Ngl I always try to avoid regex if I can do it with string methods. debugging those things is like playing some weird text adventure game where every choice is wrong.