Algorithm to capitalize the first letter of each word [duplicate]

4

I need to do this exercise to create algorithm in JavaScript:

  

"Create an algorithm to format names by leaving the first capital letters, example Rodrigo Baptista Oliveira Rodrigo Baptista"

Could someone please help me?

I can not link the function that formats words with alert .

  <button onclick="myFunction()">Clique aqui pequeno Padawan para inserir o nome.</button>

  <p id="demo"></p>

  <script>
  function myFunction() {
    var x;
    var idade = prompt("Digite o nome desejado Dudu");

  }

  String.prototype.capitalize = function(allWords) {
   return (allWords) ? // if all words
   this.split(' ').map(word => word.capitalize()).join(' ') :
   this.charAt(0).toUpperCase() + this.slice(1);
 }
 </script>
    
asked by anonymous 03.07.2017 / 03:37

2 answers

3

This function traverses the words of a string, taking into account the space and changes the first character by a mass:

function capitalizeFirstLetter(string) {
    return string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

var texto = 'rodrigo baptista de oliveira';
texto = capitalizeFirstLetter(texto);

console.log(texto)
    
03.07.2017 / 14:55
3

var Frase = "";
function myFunction() {
function primeiraLetraMaiuscula(Frase) {
   Frase  = prompt("Digite aqui");
   if (Frase != null) {
		var splitFrase = Frase.toLowerCase().split(' ');
		for (var i = 0; i < splitFrase.length; i++) {
	       splitFrase[i] = splitFrase[i].charAt(0).toUpperCase() + splitFrase[i].substring(1);     
	   }
   return splitFrase.join(' ');
   } 

}
var result = primeiraLetraMaiuscula();
//mostrará resultado no elemento de id = demo
//document.getElementById("demo").innerHTML = result;
//ou um alerta
//alert (result);
console.log(result)  
}
<button onclick="myFunction()">Clique aqui pequeno Padawan para inserir o nome.</button>
<p id="demo"></p>
    
03.07.2017 / 15:04