I\'m trying to proper case a string in javascript - so far I have this code: This doesn\'t seem to capitalize the first letter, and I\'m also stuck on how to lowercase all the l
Here's a function titleCase(string, array)
that transforms a string into title case, where the first letter of every word is capitalized except for certain prepositions, articles and conjunctions. If a word follows a colon, it will always be capitalized. You can include an optional array to ignore strings of your choice, such as acronyms.
I may have missed some exception words in the ignore
array. Feel free to add them.
function titleCase(str, array){
var arr = [];
var ignore = ["a", "an", "and", "as", "at", "but", "by", "for", "from", "if", "in", "nor", "on", "of", "off", "or", "out", "over", "the", "to", "vs"];
if (array) ignore = ignore.concat(array);
ignore.forEach(function(d){
ignore.push(sentenceCase(d));
});
var b = str.split(" ");
return b.forEach(function(d, i){
arr.push(ignore.indexOf(d) == -1 || b[i-1].endsWith(":") ? sentenceCase(d) : array.indexOf(d) != -1 ? d : d.toLowerCase());
}), arr.join(" ");
function sentenceCase(x){
return x.toString().charAt(0).toUpperCase() + x.slice(x.length-(x.length-1));
}
}
var x = titleCase("james comey to remain on as FBI director", ["FBI"]);
console.log(x); // James Comey to Remain on as FBI Director
var y = titleCase("maintaining substance data: an example");
console.log(y); // Maintaining Substance Data: An Example