Skip to content

Instantly share code, notes, and snippets.

@cvan
Created February 12, 2019 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvan/faeb0ca83073499fc1b18e7c6b3fe3da to your computer and use it in GitHub Desktop.
Save cvan/faeb0ca83073499fc1b18e7c6b3fe3da to your computer and use it in GitHub Desktop.
title-case a string into a title (containing mixed uppercased, lettercased, acronyms, initialisations)
const isAcronym = require('is-acronym');
getTitleCase = str => {
str = str || '';
return str.charAt(0).toUpperCase() + (str.substr(1) || '').toLowerCase();
};
wordsToNotCapitalise = [
'a',
'an',
'the',
'at',
'by',
'for',
'in',
'of',
'on',
'to',
'up',
'and',
'as',
'but',
'or',
'nor',
'from',
'into',
'near',
'onto',
'with'
];
toProperCase = str => (str || '').replace(/([^\W_]+[^\s-]*) */g, word => {
console.log('word', word, wordsToNotCapitalise.includes(word));
if (wordsToNotCapitalise.includes(word)) {
word = word.toLowerCase();
} else if (isAcronym(word)) {
word = word.toUpperCase();
} else if (word.toUpperCase() === word || word.toLowerCase() === word) {
word = getTitleCase(word);
}
return word;
});
words = ['Iphone', 'iPhone', 'IPHONE', 'NASA', 'Surfing', 'surfing', 'by', 'MySpace', 'HTML5', 'jo-Ann', 'smith', 'is', 'amazing', 'I', 'i', 'oN', 'on', 'ON', 'On'];
console.log(words);
console.log(words.map(toProperCase));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment