Take the last position of a split ()

2

I need to type a name in an input and show the person's name in the following format:

SURNAME (last position), So-and-so.

But I'm not able to display the name in this format, and I'm also not able to use .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>
    
asked by anonymous 06.07.2017 / 23:30

5 answers

5

Tip:

var partes = nome.split(' ');
var formatado = [partes.pop().toUpperCase(), partes.join(' ')].join(', ');

The idea is:

  • separate by spaces (as you already had)
  • create an array with 2 positions
  • in the first position put partes.pop().toUpperCase() (the last part with large print)
  • in the second position put the rest, re-positioning the spaces
  • join the parts with comma and space

Example:

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 formatado = [partes.pop().toUpperCase(), partes.join(' ')].join(', ');

  document.getElementById("formatacao").innerHTML = formatado;

}

document.querySelector("button").addEventListener('click', formatar);
input {
  width: 100%;
  padding: 10px;
}
<input id="nome" type="text" value="Antonio Manuel Antunes" />
<button>Formatar</button>
<div id="formatacao"></div>
    
07.07.2017 / 00:06
4

Approach using regex:

var nome = "Jose da Silva Sauro";

function replacer(match, m1, m2){
    return m2.toUpperCase() + ', ' + m1;
}

nome.replace(/^(.+)\b(\w+)$/g, replacer); // "SAURO, Jose da Silva"
    
07.07.2017 / 06:41
3

With split divide, and then get the last one with length-1 and join with the array all joined except the last one, using slice to cut the last and join to merge all again with spaces:

var nome = "Luis Carlos Teixeira";
var nomes = nome.split(" ");
var nomeFinal = nomes[nomes.length-1].toUpperCase() + ", " + nomes.slice(0,-1).join(" ");

console.log(nomeFinal);

In your code ultimo.toUpperCase() gives error because last is an array and not a string. Remember that slice returns an array.

In the functions used we have:

  • split(" ") part a string in an array according to the separator past
  • slice(0, -1) gets the array all but the last element
  • join (" ") joins the array in question with spaces forming a new text (string)
06.07.2017 / 23:37
2
  

I improved its function to test numeric names because if I entered 123 456 789 or Fulano de Tal 123 would accept. Credits - Sergio

function formatar() {
  var nome = document.getElementById("nome").value;
  var partes = nome.split(' ');
  var tam = (partes.length-1);

  var ultimo = partes.slice(-1);
  console.log(ultimo);
  ultimo = ultimo.toString();
  
  var HasNumericStrings = partes.filter(function(i) {
    return !isNaN(i);
  }).length > 0;

  if (HasNumericStrings) {
    alert("Digite seu nome corretamente");
    document.getElementById("nome").value = "";
    document.getElementById("nome").focus();
  } else {
    document.getElementById("formatacao").innerHTML = ultimo.toUpperCase() + ", " + partes.slice(0,-1).join(" ");
  }

}
document.querySelector("button").addEventListener('click', formatar);
<input id="nome" type="text" value="Fulano de Tal" />
<button>Formatar</button>
<div id="formatacao"></div>
  • The split() method divides a String object into an array of strings by separating the string into substrings
  • The% cos_de% property defines the number of elements in the array. It is a number one unit larger than the highest element defined in an array.
  • The length method creates a new array with all the elements that passed the test implemented by the function provided. Read more
  • The filter() method returns a string where all alphabetic characters have been converted to uppercase.
  • The toUpperCase method joins all array elements within a string. join(separador) is optional. Specifies a string to separate each element from the array. The separator is converted to a string if necessary. If omitted, the array elements are separated by a comma. If the separator is an empty string, all elements are joined without any character between them.

    In the case in question, we use a space separador Read more

06.07.2017 / 23:49
0

Only one variant of the elegant solution @ J.Guilherme (+1):

var n = "Jose da Silva Sauro";
n = n.replace(/(.+) (\w+)$/, function(_,a,b){return b.toUpperCase()+ ", "+ a});
    
07.07.2017 / 11:46