A set of utility functions for converting case.
npm install @mmckelvy/case
Convert the case of a word:
const { camelCase, snakeCase } = require('@mmckelvy/case');
camelCase('first_name');
// -> 'firstName'
snakeCase('firstName');
// -> 'first_name'
properCase('first_name');
// -> 'First name'
titleCase('first_name');
// -> 'First Name'
Handles kabob-case, extra characters, and spaces as well:
camelCase('first-name');
// -> 'firstName'
snakeCase('First--Name');
// -> 'first_name'
A frequent use case for case conversion is converting the case of object keys. case
comes with camelCaseKeys
and snakeCaseKeys
helper methods to handle this use case:
const { camelCaseKeys, snakeCaseKeys } = require('@mmckelvy/case');
const snakeToCamel = {
first_name: 'John',
last_name: 'Smith'
};
camelCaseKeys(snakeToCamel);
/* ->
{
firstName: 'John',
lastName: 'Smith'
};
*/
const camelToSnake = {
firstName: 'John',
lastName: 'Smith'
};
snakeCaseKeys(camelToSnake);
/* ->
{
first_name: 'John',
last_name: 'Smith'
};
*/
Works with arrays:
const input = [
{
first_name: 'John',
last_name: 'Smith'
},
{
first_name: 'Jane',
last_name: 'Jenkins'
},
];
camelCaseKeys(input);
/* ->
[
{
firstName: 'John',
lastName: 'Smith'
},
{
firstName: 'Jane',
lastName: 'Jenkins'
},
];
*/
To handle nested objects, pass {recursive: true}
as the second argument:
const input = {
first_name: 'John',
last_name: 'Smith',
address: {
country_of_residence: 'USA',
}
};
camelCaseKeys(input, {recursive: true});
/* ->
{
firstName: 'John',
lastName: 'Smith',
address: {
countryOfResidence: 'USA'
}
};
*/
Convert a string to camelCase.
string
The string to convert.
string
A new string in camelCase.
Convert a string to snake_case.
string
The string to convert.
string
A new string in snake_case.
Convert a string to Proper case.
string
The string to convert.
string
A new string in Proper case.
Convert a string to Title Case.
string
The string to convert.
string
A new string in Title Case.
Convert object keys to camelCase.
object
or object[]
An object or array of objects with keys you'd like to convert.
object
boolean
Recursively convert keys for nested objects and arrays.
A new object
or object[]
(does not mutate the original object
or object[]
).
Convert object keys to snake_case.
object
or object[]
An object or array of objects with keys you'd like to convert.
object
boolean
Recursively convert keys for nested objects and arrays.
A new object
or object[]
(does not mutate the original object
or object[]
).
Standardize two strings and then compare them.
string
The first string to compare.
string
The second string to compare.
function
A function applied to each string to standardize it. Defaults to snakeCase
.
boolean
true
if the strings are ===
after applying the standardization function, else false
.