Skip to content

Instantly share code, notes, and snippets.

@cawfree
Last active April 10, 2026 19:31
Show Gist options
  • Select an option

  • Save cawfree/c08c10f6f2e7b2c8d225d88b031a03ce to your computer and use it in GitHub Desktop.

Select an option

Save cawfree/c08c10f6f2e7b2c8d225d88b031a03ce to your computer and use it in GitHub Desktop.
Convert between Camel Case (camelCase) and Snake Case (snake_case) in ES6
export const toCamelCase = (e) => {
return e.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
};
export const toSnakeCase = (e) => {
return e.match(/([A-Z])/g).reduce(
(str, c) => str.replace(new RegExp(c), '_' + c.toLowerCase()),
e
)
.substring((e.slice(0, 1).match(/([A-Z])/g)) ? 1 : 0);
};
@MaxMonteil
Copy link
Copy Markdown

With the second argument of replace taking a function that gives you the match itself, you can get a one liner for snake case:

export const camelToSnakeCase = e => e.replace(/([A-Z])/g, (_, c) => `_${c.toLowerCase()}`);

similar for camel case:

export const snakeToCamelCase = e => e.replace(/_([a-z])/g, (_, c) => `${c.toUpperCase()}`);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment