Last active
April 23, 2018 20:33
-
-
Save kirkaracha/595c22fa585834d5706580ba9ec1c2e4 to your computer and use it in GitHub Desktop.
Converts a string to title case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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