Created
February 12, 2019 00:37
-
-
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)
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
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