Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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_name

kebab-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-color

Back 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
fontSize

Common mistake

Without the g flag only the first match is replaced:

console.log('userLastLogin'.replace(/[A-Z]/, (letter) => '_' + letter.toLowerCase()));

Output:

user_lastLogin

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.