Snake case to camel case:
function snakeToCamel(string) { return string.replace(/(_\w)/g, function(m){ return m[1].toUpperCase(); }); }
… and camel case to snake case:
function camelToSnake(string) { return string.replace(/[\w]([A-Z])/g, function(m) { return m[0] + "_" + m[1]; }).toLowerCase(); }
The method above fails on some strings.
This works better:
function snakeToCamel(string) {
return string.replace(/([-_][a-z])/ig, ($1) => {
return $1.toUpperCase()
.replace(\’-\’, \’\’)
.replace(\’_\’, \’\’);
});
}
Source: https://matthiashager.com/converting-snake-case-to-camel-case-object-keys-with-javascript
Great post!
Just a small typo:
– Your function is named \”camelToSake\” and not \”camelToSnake\”
Thank you for pointing me this out! It is fixed now 🙂