Skip to content

Instantly share code, notes, and snippets.

@cawfree
Last active July 16, 2024 21:26
Show Gist options
  • Save cawfree/c08c10f6f2e7b2c8d225d88b031a03ce to your computer and use it in GitHub Desktop.
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);
};
@looshch
Copy link

looshch commented Apr 19, 2024

thanks ❤️

@al-vincent
Copy link

al-vincent commented May 17, 2024

Thanks, this is great!

One FYI - for isSnakeCase, the reduce will fail if the input is already in snake case (e.g. toSnakeCase('foo'), toSnakeCase('foo_bar'). I added

if (e.toLowerCase() === e) {
    return e;
}

at the start, but there's probably a more elegant way.

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