We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

iTony on 05/22/08


Tagged

titles capitalization camel-case


Versions (?)


Nice Caps Titles


Published in: JavaScript 


URL: http://ejohn.org/files/titleCaps.js

I haven't take a very good look to the code, but I put it here for future reference.

  1. /*
  2.  * Title Caps
  3.  *
  4.  * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
  5.  * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
  6.  * License: http://www.opensource.org/licenses/mit-license.php
  7.  */
  8.  
  9. (function(){
  10. var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
  11. var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
  12.  
  13. this.titleCaps = function(title){
  14. var parts = title.split(/([:.;?!] |(?: |^)["Ò])/);
  15.  
  16. for ( var i = 0; i < parts.length; i++ ) {
  17. parts[i] = parts[i]
  18. .replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
  19. return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
  20. })
  21. .replace(RegExp("\\b" + small + "\\b", "ig"), lower)
  22. .replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
  23. return punct + upper(word);
  24. })
  25. .replace(RegExp("\\b" + small + punct + "$", "ig"), upper);
  26. }
  27.  
  28. return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
  29. .replace(/(['Õ])S\b/ig, "$1s")
  30. .replace(/\b(AT&T|Q&A)\b/ig, function(all){
  31. return all.toUpperCase();
  32. });
  33. };
  34.  
  35. function lower(word){
  36. return word.toLowerCase();
  37. }
  38.  
  39. function upper(word){
  40. return word.substr(0,1).toUpperCase() + word.substr(1);
  41. }
  42. })();

Report this snippet 

You need to login to post a comment.