i7yoxq
Last Updated: February 25, 2016
·
1.785K
· felclef

Capitalize string (even latin names)

As you may know, in Javascript we can use a callback function which defines the replacement string in String.replace, as seem in https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Replace.

So, a tip for you guys: how to prototype capitalize and capitalizeName:

String.prototype.capitalize = function (){
    return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(_m, _p1, _p2){ return _p1+_p2.toUpperCase();});
};

The _m stands for match, _pN stands for "each of the group matches in the regex" (the values between parentheses).

Now that we can capitalize strings, the trick is to treat the prepositions of latin names, like "do, da, dos, das, de" -- which is very common in Brazil, Italy, Spain, etc. ;D

String.prototype.capitalizeName = function (){
    return this.capitalize().replace( /(\sd(a|e|i|o|u)?s?\s?)/gi , function(_m, _p1){ return _p1.toLowerCase(); });
};

Try it in your browser's Javascript console!

[]

Bruno J. Araujo

  • I'm workin' on name patterns like "d'Água" :P