Skip to content

Instantly share code, notes, and snippets.

@rodrigojusto
Created November 14, 2017 17:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigojusto/cb61e1ea07c7123e9c9533c8f1c2b0c2 to your computer and use it in GitHub Desktop.
Save rodrigojusto/cb61e1ea07c7123e9c9533c8f1c2b0c2 to your computer and use it in GitHub Desktop.
String Capitalize names
/** Prototipagem para capitalizar nomes próprios, levando em consideração que
não se capitalize as preposições, artigos e outros elementos que não sejam
Nomes proprios.
Ex: "rodrigo SOUZA juSTO".capitalizeNames() => "Rodrigo Souza Justo";
"osama bin ladeN".capitalizeNames() => "Osama bin Laden";
"PiErRo DELLA francesca".capitalizeNames() => "Pierro della Francesca";
"manfred von richthoffen".capitalizeNames() => "Manfred von Hichthoffen";
"JOÃO DA SILVA".capitalizeNames() => "João da Silva";
existe algumas exceções, como por exemplo, o nome da peça La Traviata, onde
o artigo do italiano "La" encontra-se no inicio do nome, portanto.
**/
/** Aplica expressões regulares em contrações de nomes */
const regex = /^(.)|\s+(.)|'+(.)/g;
String.prototype.capitalizeNames = function () {
capitalized = [];
nomeArray = this.ucwords().split(" ");
articleAndPrepositions = ["El", "La", "Le", "Les", "Los", "Os", "A","As", "E", "Da","De","Di","Do","Du","Das","Dos","Deu","Der","Van","Von", "Bin", "Della"];
nomeArray.forEach(function(nome){
if(articleAndPrepositions.indexOf(nome)!= -1){nome = nome.toLowerCase();}
capitalized.push(nome);
});
return capitalized.join(" ");
};
String.prototype.ucwords=function(){return(this.toLowerCase()).replace(regex,function($1){return $1.toUpperCase();});};
String.prototype.capitalize = function(){return this.charAt(0).toUpperCase() + this.slice(1);};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment