Take the last position of a split()

Asked

Viewed 2,432 times

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>

  • 2

    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()

5 answers

5

Suggestion:

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 partes.pop().toUpperCase() (the last part with large letter)
  • in the second position put the rest, re-placing 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>

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"
  • \b? End of word?

  • 1

    yes, regex breaks the string into 2 parts: one before and one after the last space

  • 1

    never successfully used the \b, good to see a functional example

3

With the split divide, and then take the last with length-1 and joins with the whole array except the last one, using the slice to cut the last and the join to unite everything 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 last Slice returns an array.

In the functions used we have:

  • split(" ") breaks a string into an array according to the separator past tense
  • slice(0, -1) gets the whole array except the last element
  • join (" ") unites the whole array with spaces forming a new text(string)
  • and how do I turn this array into a string? Or I have to use another method to get the last position of the name?

  • If you already have an array, the partes the last name is partes[partes.length-1]

  • It turns out that you have a string contained within an array, so you don’t have to transform anything, just access the position of the array correctly, but personally I find the @Isac response more secure and correct :)

  • ok, can you just explain to me why (names.Slice(0 , -1) returns me to first and second position? -1 shouldn’t I return to last? And what is . Join(" ")? I didn’t understand these two parts. Thank you for all your help :).

  • Yes I can complete too. The slice(0, -1) gets the array all but the last position, and the join(" ") joins the entire array by pasting the values with space, forming a new string.

  • Isac, but why does Slice(0) take the whole array? I thought (0) took position 1, or is it just [0] that does it? What’s the difference between (0) and [0]?

  • Whore of 0 at the end -1. The 0 indicates where it starts.

Show 2 more comments

2

I improved its function to test numerical names since it was inserted 123 456 789 or Fulano de Tal 123would 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 method split() splits a String object into an array of strings by separating the string into substrings
  • The estate length defines the number of elements of the matrix. It is a number one unit greater than the highest element defined in a matrix.
  • The method filter() creates a new array with all the elements that passed the test implemented by the provided function. Read more
  • The method toUpperCase returns a string where all alphabetic characters have been capitalized.
  • The method join(separador) joins all array elements within a string. separador is optional. Specifies a string to separate each element of the array. The separator is converted into a string if necessary. If omitted, the array elements are separated with a comma. If the separator is an empty string, all elements are joined with no character between them.

    In the case in question we use a space join(" ") Read more

  • 5

    Take care Leo, your answer answers only part of what was asked

  • @Marceloboni I’ve taken proper care of :)

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});

Browser other questions tagged

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