Andrew Nguyen Andrew Nguyen - 1 year ago 98
Javascript Question

Grabbing the last names of players in array using split, splice


I'm trying to get just the last names of the players in a series of spans and then be able to store those lastNames in their own variable
var lastNameA
var lastNameB

Here is an example of some of the names,
Pierre Turgeon
Larry Patey
Kelly Shattenkirk
Barret Jackman
Alex Pietrangelo
Jacques Plante
and in one special case, the person's last name is
St. Marseille


In many cases, I will want the even number items in the array, but with St. Marseille, I want both the

// Grabs the names of all the players in the span
// Then, it joins the names together with a comma and a space
var fullNames = $("li span").map(function(){
return $(this).text();
}).get().join(", ");

// This breaks a name into their first name and last name
fullNames.split(" ");

Answer Source

Well, you can split only at the first space, but then you'll run into trouble with names like John Steven Murphy, where the last name is just "Murphy." Then there are names like Gerard van der Sanden or Angelina de la Vega and such, where there is not just one space but two in the family name.

Bottom-line, it's always going to be wrong for certain inputs if you don't have a clear delimiter.

But if you work on the basis that the "first" name won't have any spaces (which is a flawed assumption):

var lastNames = $("li.span").map(function() {
    var name = $(this).text();
    var index = name.indexOf(" ");
    return index == -1 ? name : name.substring(index + 1);

var lastNames = $("li.span").map(function() {
  var name = $(this).text();
  var index = name.indexOf(" ");
  return index == -1 ? name : name.substring(index + 1);
console.log("Note that it gets John Steven Murphy wrong, see answer text for details.");
  <li class="span">Pierre Turgeon</li>
  <li class="span">Larry Patey</li>
  <li class="span">Kelly Shattenkirk</li>
  <li class="span">Barret Jackman</li>
  <li class="span">Alex Pietrangelo</li>
  <li class="span">Jacques Plante</li>
  <li class="span">Michel St. Marseille</li>
  <li class="span">Gerard van der Sanden</li>
  <li class="span">Angelina de la Vega</li>
  <li class="span">John Steven Murphy</li>
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download