Skip to content

Instantly share code, notes, and snippets.

@kirkaracha
Last active April 23, 2018 20:33
Show Gist options
  • Save kirkaracha/595c22fa585834d5706580ba9ec1c2e4 to your computer and use it in GitHub Desktop.
Save kirkaracha/595c22fa585834d5706580ba9ec1c2e4 to your computer and use it in GitHub Desktop.
Converts a string to title case
function titleCase (title) {
const smallWords = [
'a',
'an',
'and',
'at',
'but',
'by',
'else',
'for',
'from',
'if',
'in',
'into',
'is',
'nor',
'of',
'off',
'on',
'or',
'out',
'over',
'the',
'then',
'to',
'when',
'with'
];
const specialWords = [
'I',
'II',
'III',
'IV',
'V',
'VI',
'VII',
'UK',
'US'
];
const punctuation = [
'.',
'-',
':',
'!',
'?'
];
let words = title.toLowerCase().split(' ');
for (let i = 0; i < words.length; i++) {
let word = words[i];
let lastCharacterPreviousWord = words[i - 1].slice(-1);
if (
!smallWords.includes(word) ||
!specialWords.includes(word) ||
punctuation.includes(lastCharacterPreviousWord),
i === 0
) {
capitalizeFirstCharacter(words[i]);
}
}
return title;
}
function capitalizeFirstCharacter(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment