Created
March 11, 2014 18:42
-
-
Save dbernar1/9492294 to your computer and use it in GitHub Desktop.
titleCase
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
function break_into_words( text ) { | |
return text.split( ' ' ).filter( function(word) { return word !== ''; } ); | |
} | |
function add( element, to_array ) { | |
to_array.push( element ); | |
} | |
function space_separated( array ) { | |
return array.join( ' ' ); | |
} | |
String.prototype.in_lower_case = function( ) { return this.toLowerCase(); }; | |
String.prototype.is_one_of_the = function( words ) { | |
if ( 'undefined' === typeof words ) { | |
words = ''; | |
} | |
var words_as_array_in_lowercase = words.split( ' ' ).map( function(word) { return word.in_lower_case(); } ); | |
return -1 !== words_as_array_in_lowercase.indexOf( this.in_lower_case() ); | |
}; | |
String.prototype.first_letter_capitalized_rest_lowercased = function () { | |
return this[0].toUpperCase() + this.slice( 1 ).in_lower_case(); | |
}; | |
function titleCase(title, minorWords) { | |
var title_cased_title = '', | |
words_in_title = break_into_words( title ), | |
case_corrected_words_in_title = []; | |
words_in_title.forEach( function( word, index ) { | |
var this_is_not_the_first_word_in_the_title = index !== 0; | |
if ( | |
word.is_one_of_the( minorWords ) | |
&& this_is_not_the_first_word_in_the_title | |
) { | |
add( word.in_lower_case(), case_corrected_words_in_title ); | |
} else { | |
add( word.first_letter_capitalized_rest_lowercased(), case_corrected_words_in_title ); | |
} | |
} ); | |
return space_separated( case_corrected_words_in_title ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment