Skip to content

Instantly share code, notes, and snippets.

@belsrc
Created January 24, 2018 05:29
Show Gist options
  • Save belsrc/f7a574e3057b4ed4527a0a9c76e7ed30 to your computer and use it in GitHub Desktop.
Save belsrc/f7a574e3057b4ed4527a0a9c76e7ed30 to your computer and use it in GitHub Desktop.
const isString = value => typeof value === 'string' || value instanceof String;
/*
camelCase('camel case'); // camelCase
camelCase('camel_case'); // camelCase
camelCase('camel-case'); // camelCase
*/
const camelCase = str => {
if(!isString(str)) {
return '';
}
const s = str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0, 1).toLowerCase() + s.slice(1);
};
/*
kebabCase('kebab case'); // kebab-case
kebabCase('kebabCase'); // kebab-case
kebabCase('kebab_case'); // kebab-case
*/
const kebabCase = str =>
isString(str) ?
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('-') :
'';
/*
snakeCase('snake case'); // snake_case
snakeCase('snakeCase'); // snake_case
snakeCase('snake-case'); // snake_case
*/
const snakeCase = str =>
isString(str) ?
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_') :
'';
/*
titleCase('the old man and the sea'); // The Old Man and the Sea
titleCase('theOldManAndTheSea'); // The Old Man and the Sea
titleCase('the-old-man-and-the-sea'); // The Old Man and the Sea
titleCase('the_old_man_and_the_sea'); // The Old Man and the Sea
*/
const titleCase = str => {
const lower = [
'and', 'or', 'nor', 'but', 'a', 'an', 'the', 'as', 'at', 'by', 'for', 'in', 'of', 'on', 'per', 'to', 'is',
];
return isString(str) ?
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.map((x, i) =>
lower.includes(x.toLowerCase()) && i !== 0 ? x.toLowerCase() : x)
.join(' ') :
'';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment