Skip to content

Instantly share code, notes, and snippets.

@johanfriis
Created May 18, 2013 20:10
Show Gist options
  • Save johanfriis/5605630 to your computer and use it in GitHub Desktop.
Save johanfriis/5605630 to your computer and use it in GitHub Desktop.
Convert a string to a human readable title string #snippet
/*
* Convert a string into a human readable title
*
* This function borrows heavily from sugar.js
* http://sugarjs.com/
*
* titleize("man from the boondocks") -> Man from the Boondocks
* titleize("x-men: the last stand") -> X Men: The Last Stand
* titleize("TheManWithoutAPast") -> The Man Without a Past
* titleize("raiders_of_the_lost_ark") -> Raiders of the Lost Ark
*
*/
var titleize = function(str) {
var punctuation = /[.:;!]$/;
var hasPunctuation;
var hadPunctuation;
var isFirstOrLast;
var downcased = [
'and', 'or', 'nor', 'a', 'an', 'the', 'so', 'but', 'to', 'of', 'at',
'by', 'from', 'into', 'on', 'onto', 'off', 'out', 'in', 'over',
'with', 'for'
];
// convert hyphens and camelCase to spaces
return str
.replace(/[\-\s]+/g, ' ')
.replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1 $2')
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
.replace(/_/g, ' ')
.toLowerCase()
.replace(/^\W*[a-z]/, function (w) {
return w.toUpperCase();
})
.trim()
.each(/\S+/g, function (word, index, words) {
hasPunctuation = punctuation.test(word);
isFirstOrLast = index === 0
|| index == words.length - 1
|| hasPunctuation
|| hadPunctuation;
hadPunctuation = hasPunctuation;
if (isFirstOrLast || downcased.indexOf(word) === -1) {
//capitalize
return word.replace(/^\W*[a-z]/, function (w) {
return w.toUpperCase()});
} else {
return word;
}
})
.join(' ')
;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment