Results 1 to 1 of 1

Thread: Title - Initial Caps

  1. #1
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default Title - Initial Caps

    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:

    Code:
    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){
    				title.push(words[w]);
    			} 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;
    	skip.reverse();
    	while(--s > -1){so[skip[s]] = true;}
    	return so;
    })();
    Last edited by jscheuer1; 02-07-2017 at 08:56 PM. Reason: code improvement
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Similar Threads

  1. Replies: 0
    Last Post: 01-31-2015, 03:06 PM
  2. Fadeslideshow initial color
    By bento06 in forum Dynamic Drive scripts help
    Replies: 3
    Last Post: 01-14-2010, 10:58 PM
  3. Resolved setInterval initial value
    By nicksalad in forum JavaScript
    Replies: 3
    Last Post: 10-28-2009, 07:20 AM
  4. Caps Lock - Not Sure If One Exists
    By banka in forum Looking for such a script or service
    Replies: 1
    Last Post: 03-07-2008, 03:52 AM
  5. How to set initial y value on div scroll?
    By Mistrel in forum JavaScript
    Replies: 2
    Last Post: 06-14-2006, 05:32 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •