Skip to content

Instantly share code, notes, and snippets.

@LiamKarlMitchell
Last active October 4, 2019 05:13
Show Gist options
  • Save LiamKarlMitchell/d2ac10da82bd7b5cf8a90a2d5104d132 to your computer and use it in GitHub Desktop.
Save LiamKarlMitchell/d2ac10da82bd7b5cf8a90a2d5104d132 to your computer and use it in GitHub Desktop.
Capitalize peoples names jQuery snippet.
// Scenario:
// Users enter name in all lowercase or all uppercase it fixes the case.
// This isn't 100% suitable for all names but eh whatever!
// Attempts to resepect intentional ' and " and intentional multiple case.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp(String.fromCharCode(92)+"b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
// Needed it for a contact form 7 in wordpress, thats why it looks weird and has no comments as it was stripping my \ character or changing new lines to <br> gah!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment