Algorithm to capitalize the first letter of each word

Asked

Viewed 1,415 times

4

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

"Create an algorithm to format names leaving the first letters uppercase, example Oliveira Baptist Law => Rodrigo Baptista De Oliveira"

Could someone please help me?

I can’t connect the function that formats words with the 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>
  • Welcome to [pt.so]. A good practice to start a healthy discussion is to do the [tour] if you haven’t already done it, and read the [Ask] guide. Start by following these recommendations, especially knowing what types of questions to ask, how to create a minimal example that is complete and verifiable, and even what to do when someone answers you.

  • What have you tried to do? Post your code, even if it is full of errors.

  • This way: https://jsfiddle.net/56un1w9v/1/ I cannot connect the function that formats words with Alert.

2 answers

3


This function traverses the words of a string, taking into account the space and swapping the first character for the main:

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)

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>

  • Thanks Leo and Lucas,with the adaptations the code worked beautifully.Thank you very much you helped me a lot :).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.