Last active
May 31, 2017 20:09
-
-
Save mcansh/3d9aec652d42b57298f984d1dc6681c8 to your computer and use it in GitHub Desktop.
Converts a String to Titlecase.
This file contains 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 toTitleCase(string) { | |
if (!string) { | |
return 'no string was found'; | |
} | |
let newString = string; | |
const lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With']; | |
const uppers = ['TV']; | |
newString = newString.replace(/([^\W_]+[^\s-]*) */g, (txt) => { | |
return `${txt.charAt(0).toUpperCase()}${txt.substr(1).toLowerCase()}`; | |
}); | |
lowers.forEach((lower) => { | |
newString = newString.replace(new RegExp(`\\s${lower}\\s`, 'g'), (txt) => { | |
return txt.toLowerCase(); | |
}); | |
}); | |
uppers.forEach((upper) => { | |
newString = newString.replace(new RegExp(`\\b${upper}\\b`, 'g'), upper.toUpperCase()); | |
}); | |
return newString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment