Created
May 18, 2013 20:10
-
-
Save johanfriis/5605630 to your computer and use it in GitHub Desktop.
Convert a string to a human readable title string #snippet
This file contains hidden or 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
/* | |
* 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