Last active
August 22, 2017 22:55
-
-
Save mattbontrager/6972d06f2315a19f0cf0 to your computer and use it in GitHub Desktop.
Title Case a string; one for automating method calls, another for titles of articles, books, etc.
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
/** | |
* use this helper function to convert captured html element attributes | |
* (or whatever) to a title cased string. | |
* | |
* @date 2017-08-22 | |
* @author mattbontrager | |
* @param {String} string [the string to be converted to CamelCase] | |
* @return {String} [the CamelCased string] | |
*/ | |
function titleCaseWithSymbols(string) { | |
if (!string) { | |
return false; | |
} | |
var spaced = string.replace(/[-_]/g, " "); | |
return spaced.replace(/\w\S*/g, function(txt) { | |
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); | |
}); | |
} | |
/** | |
* This is a helper function that correctly converts a string of text to Title Case. | |
* @date 2017-08-22 | |
* @author mattbontrager | |
* @param {String} string the string to be converted to title case | |
* @return {String} the converted string | |
*/ | |
function titleCase(string) { | |
if (!string) { | |
return false; | |
} | |
var doNotCapitalize = ["a", "an", "the", "at", "by", "for", "in", "of", "on", "to", "up", "and", "as", "but", "or", "nor"], | |
space = ' ', | |
words = string.split(' '), // array | |
numOfWords = words.length - 1, | |
returnArray = string.toLowerCase().split(' ').map(function(word) { | |
var isInArray = doNotCapitalize.indexOf(word); | |
return (isInArray !== -1) ? word: word.replace(word[0], word[0].toUpperCase()); | |
}), | |
firstWord = returnArray[0], | |
lastWord = returnArray[numOfWords], | |
returnString; | |
// Capitalize the first and last word regardless of whether or not they're in doNotCapitalize | |
returnArray[0] = firstWord.replace(firstWord[0], firstWord[0].toUpperCase()); | |
returnArray[numOfWords] = lastWord.replace(lastWord[0], lastWord[0].toUpperCase()); | |
// Convert the array of words back to a string | |
returnString = returnArray.join(' '); | |
return returnString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment