How to convert camelCase to snake_case and back
Short answer
Find each capital letter and put an underscore before it:
const snake = 'firstName'.replace(/[A-Z]/g, (letter) => '_' + letter.toLowerCase());
console.log(snake);Output:
first_namekebab-case
For CSS classes and URLs a hyphen is used instead of an underscore:
const kebab = 'backgroundColor'.replace(/[A-Z]/g, (letter) => '-' + letter.toLowerCase());
console.log(kebab);Output:
background-colorBack to camelCase
Find an underscore or a hyphen followed by a letter and replace the pair with the capital letter:
const toCamel = (text) => text.replace(/[_-]([a-z])/g, (match, letter) => letter.toUpperCase());
console.log(toCamel('user_last_login'));
console.log(toCamel('font-size'));Output:
userLastLogin
fontSizeCommon mistake
Without the g flag only the first match is replaced:
console.log('userLastLogin'.replace(/[A-Z]/, (letter) => '_' + letter.toLowerCase()));Output:
user_lastLoginFunctions used in this recipe
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- String.prototype.toLowerCase — Converts a string to lowercase.