Skip to content

Instantly share code, notes, and snippets.

@jenhuls
Created March 27, 2022 09:50
Show Gist options
  • Save jenhuls/294a15bf0c829f83c3cfcad68586cb37 to your computer and use it in GitHub Desktop.
Save jenhuls/294a15bf0c829f83c3cfcad68586cb37 to your computer and use it in GitHub Desktop.
[jQuery Text to Title Case] #jquery
(function($) {
$.fn.toTitleCase = function() {
return $(this).each(function() {
var ignore = "and,the,in,with,an,or,at,of,a,to,for".split(",");
var theTitle = $(this).text();
var split = theTitle.split(" ");
for (var x = 0; x < split.length; x++) {
if (x > 0) {
if (ignore.indexOf(split[x].toLowerCase()) < 0) {
split[x] = split[x].replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
} else {
split[x] = split[x].replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
}
title = split.join(" ");
$(this).text(title);
});
};
$(".text__title-case").toTitleCase();
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment