Last active
July 16, 2024 21:26
-
-
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 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
Thanks, this is great!
One FYI - for
isSnakeCase
, thereduce
will fail if the input is already in snake case (e.g.toSnakeCase('foo')
,toSnakeCase('foo_bar')
. I addedat the start, but there's probably a more elegant way.