View Full Version : Title - Initial Caps

02-07-2017, 04:11 AM
My code editor has an option where you can highlight a string and have it do that, convert to "Title - Initial Caps". But it's not sensitive to conventions or choices in that it will simply lower the case of everything, then make the first letter of each word upper case. I thought it would be fun to make a function that could optionally preserve the existing case of the other letters and that would skip certain words that generally are not capitalized in titles. I'm sure it's not perfect, but it is pretty good, and can be edited to include other words to be skipped and/or to take into account other conventions or contingencies:

function titleize(str, preservecase){
if(!preservecase){str = str.toLowerCase();}
var words = str.split(/\b/), title = [], wc = words.length, w = -1, firstword;
if(wc > 1){
while(++w < wc){if(/\w/.test(words[w])){firstword = w; w = -1; break;}}
while(++w < wc){
if((words[w].length < 2 || titleize.skip[words[w].toLowerCase()]) && w > firstword){
} else {
title.push(words[w].charAt(0).toUpperCase() + words[w].substring(1));
return title.join('');
return str.charAt(0).toUpperCase() + str.substring(1);
titleize.skip = (function(){
var skip = ['an', 'and', 'as', 'at', 'but', 'by', 'do', 'for', 'from', 'in', 'into', 'nor', 'on', 'or', 'the', 'to', 'with'],
so = {}, s = skip.length;
while(--s > -1){so[skip[s]] = true;}
return so;