Nice Caps Titles


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. })();

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.