Skip to content

Latest commit

 

History

History
84 lines (64 loc) · 1.52 KB

79.convert-snake_case-to-camelCase.md

File metadata and controls

84 lines (64 loc) · 1.52 KB

79. convert snake_case to camelCase

Problem

https://bigfrontend.dev/problem/convert-snake_case-to-camelCase

Problem Description

Do you prefer snake_case or camelCase ?

Anyway, please create a function to convert snake_case to camcelCase.

snakeToCamel('snake_case');
// 'snakeCase'
snakeToCamel('is_flag_on');
// 'isFlagOn'
snakeToCamel('is_IOS_or_Android');
// 'isIOSOrAndroid'
snakeToCamel('_first_underscore');
// '_firstUnderscore'
snakeToCamel('last_underscore_');
// 'lastUnderscore_'
snakeToCamel('_double__underscore_');
// '_double__underscore_'

contiguous underscore __, leading underscore _a, and trailing underscore a_ should be kept untouched.

Solution

/**
 * @param {string} str
 * @return {string}
 */
function snakeToCamel(str) {
  return str.replace(/[a-z]_[a-z]/gi, (match) => {
    return match[0] + match[2].toUpperCase();
  });
}

Refactored Solution

/**
 * @param {string} str
 * @return {string}
 */
function snakeToCamel(str) {
  return str.replace(/([^_])_([^_])/g, (_, before, after) => {
    return before + after.toUpperCase();
  });
}

Solution with Lookbehind

/**
 * @param {string} str
 * @return {string}
 */
function snakeToCamel(str) {
  return str.replace(/(?<=[a-z])_[a-z]/gi, (match) => {
    return match[1].toUpperCase();
  });
}

Reference

Problem Discuss