Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Regex For Human Names

I'm looking for a good JavaScript RegEx to convert names to proper cases. For example:

John SMITH = John Smith

Mary O'SMITH = Mary O'Smith

E.t MCHYPHEN-SMITH = E.T McHyphen-Smith  

John Middlename SMITH = John Middlename SMITH

Well you get the idea.

Anyone come up with a comprehensive solution?

like image 889
raccettura Avatar asked Sep 06 '25 03:09

raccettura


1 Answers

Something like this?

function fix_name(name) {
    var replacer = function (whole,prefix,word) {
        ret = [];
        if (prefix) {
            ret.push(prefix.charAt(0).toUpperCase());
            ret.push(prefix.substr(1).toLowerCase());
        }
        ret.push(word.charAt(0).toUpperCase());
        ret.push(word.substr(1).toLowerCase());
        return ret.join('');
    }
    var pattern = /\b(ma?c)?([a-z]+)/ig;
    return name.replace(pattern, replacer);
}
like image 58
Markus Jarderot Avatar answered Sep 07 '25 19:09

Markus Jarderot