JS: Turn text into TitleCase


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

I love this script. It's perfect for anyone trying to transforms headlines into some sort of Title Case format without using CSS


Copy this code and paste it in your HTML
  1. /* To Title Case 1.1.1
  2.  * David Gouch <http://individed.com>
  3.  * 23 May 2008
  4.  * License: http://individed.com/code/to-title-case/license.txt
  5.  *
  6.  * In response to John Gruber's call for a Javascript version of his script:
  7.  * http://daringfireball.net/2008/05/title_case
  8.  */
  9.  
  10. String.prototype.toTitleCase = function() {
  11. return this.replace(/([\w&`'‘’"“[email protected]:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title) {
  12. if (index > 0 && title.charAt(index - 2) !== ":" &&
  13. match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1)
  14. return match.toLowerCase();
  15. if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1)
  16. return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
  17. if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 ||
  18. title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
  19. return match;
  20. return match.charAt(0).toUpperCase() + match.substr(1);
  21. });
  22. };

URL: http://individed.com/code/to-title-case/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.