Created
September 27, 2011 07:28
-
-
Save timoxley/1244534 to your computer and use it in GitHub Desktop.
jQuery titlecase plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.