change-case
change-case copied to clipboard
Leading underscores are not preserved
First off, thanks for the lib, it's fantastic! 😄
So, leading underscores are not preserved (even with snakeCase):
changeCase.snakeCase('private'); //=> 'private'
changeCase.snakeCase('_private'); //=> 'private'
changeCase.snakeCase('private_key'); //=> 'private_key'
changeCase.snakeCase('_private_key'); //=> 'private_key'
changeCase.snakeCase('privateKey'); //=> 'private_key'
changeCase.snakeCase('_privateKey'); //=> 'private_key'
changeCase.camelCase('private_key'); //=> 'privateKey'
changeCase.camelCase('_private_key'); //=> 'privateKey'
There's a strong argument to be made that this is expected behavior for camelCase specifically, but I think for snakeCase it is arguably not expected behavior; leading underscores are pretty widely used as a convention to denote privacy, and the presence of a leading underscore doesn't conflict with the rules of "snake case", unless I'm mistaken.
Thoughts?
If this is intended behavior/"wontfix", would you consider an option parameter to preserve leading underscores?
I think this makes sense, it is interesting because it's possible that basing everything on a no-case standard to switch between has caused issues like this. I'll look into separating them back apart instead, edge cases like this are hard to handle otherwise.
I am using this in a GraphQL API to transform the response to snake_case (which legacy code expects).
This works fine for 'normal' data, but the 'special' data (e.g. __typename) gets trashed by this function.
An option to ignore leading underscores would be great if possible.
@adam-h I was able to achieve it in the current version using the built-in options, though it's not elegant (and V8 only due to look behinds):
{ stripRegexp: /(?<!^_*)[^A-Z0-9]+/gi }
Edit: Added a solution that solves bugs with the previous version.
The latest release adds a dedicated prefixCharacters option, currently defaulting to "" but can be overridden to retain "_" or any other character.