2
I need to enter a name in an input and display the person’s name in the following format:
SURNAME(last position), So-and-so.
But I’m not being able to show the name in this format, and I’m also not being able to use the . toUpperCase() in the "last" variable as it is giving error.
function formatar() {
var nome = document.getElementById("nome").value;
if (nome === "" || Number(nome)) {
alert("Digite seu nome corretamente");
document.getElementById("nome").value = "";
document.getElementById("nome").focus();
return;
}
var partes = nome.split(" ");
var tam = partes.length;
var text;
var ultimo = partes.slice(-1);
console.log(ultimo);
for (i = 0; i < tam; i++) {
text = ultimo.toUpperCase() + ", " + partes;
}
document.getElementById("formatacao").innerHTML = text;
}
<input id="nome">
<button type="button" onclick="formatar()">Formatar</button>
<div id="formatacao"></div>
The problem with your code is that the variable
ultimo
is an array and not a string, to access correctly should do:ultimo[0].toUpperCase()
– MarceloBoni