6.4.09

Javascript to correct case for Name fields

Though this might be a simple script, I felt it always good to share a re-usable code

Text Entered - o'reAlly jack daniels mc donald
Changes to - O'Really Jack Daniels Mc Donald


function CorrectNamingCase(control) {
var pattern = /(\w)?(\w*)?(\W\w)?(\S*)/; // a letter, and then rest of word, special character word, none or more letters

var a = control.value.split(/\s+/g); // split the sentence into an array of words

for (i = 0; i < a.length; i++) {
var parts = a[i].match(pattern); // just a temp variable to store the fragments in.

var firstLetter = parts[1].toUpperCase();
var firstWord = parts[2].toLowerCase();
var specialWord = parts[3].toUpperCase();
var restOfWord = parts[4].toLowerCase();

a[i] = firstLetter + firstWord + specialWord + restOfWord; // re-assign it back to the array and move on
}
control.value = a.join(' '); // join it back together
}


0 comments:

Post a Comment