Skip to content

Instantly share code, notes, and snippets.

@timoxley
Created September 27, 2011 07:28
Show Gist options
  • Save timoxley/1244534 to your computer and use it in GitHub Desktop.
Save timoxley/1244534 to your computer and use it in GitHub Desktop.
jQuery titlecase plugin
/*
* Convert HTML elements titlecase with jQuery
* (jQuery plugin version of http://individed.com/code/to-title-case/js/to-title-case.js)
*/
jQuery.fn.titlecase = function() {
return this.each(function() {
var newText = jQuery(this).text().replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g,
function(match, p1, index, title) {
if (index > 0 && title.charAt(index - 2) !== ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1) return match.toLowerCase();
if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1) return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1) return match;
return match.charAt(0).toUpperCase() + match.substr(1);
});
jQuery(this).text(newText)
});
};
// Example
$(function() {
$('h1, h2, h3, h4').titlecase();
});
@timoxley
Copy link
Author

Doesn't work on text nested inside child nodes (eg. <h1><a>some text</a></h1> becomes <h1>some text</h1>) (in fact it removes all child nodes, and simply replaces them with their text component) This is sucky behaviour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment