Last active
April 10, 2026 19:31
-
-
Save cawfree/c08c10f6f2e7b2c8d225d88b031a03ce to your computer and use it in GitHub Desktop.
Convert between Camel Case (camelCase) and Snake Case (snake_case) in ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With the second argument of
replacetaking a function that gives you the match itself, you can get a one liner for snake case:similar for camel case: