Skip to content

Instantly share code, notes, and snippets.

@mcansh
Last active May 31, 2017 20:09
Show Gist options
  • Save mcansh/3d9aec652d42b57298f984d1dc6681c8 to your computer and use it in GitHub Desktop.
Save mcansh/3d9aec652d42b57298f984d1dc6681c8 to your computer and use it in GitHub Desktop.
Converts a String to Titlecase.
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