Andrew Nguyen Andrew Nguyen - 2 months ago 7
Javascript Question

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

Objective



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


scripts.js



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


// 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

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);
}).get();

var lastNames = $("li.span").map(function() {
  var name = $(this).text();
  var index = name.indexOf(" ");
  return index == -1 ? name : name.substring(index + 1);
}).get();
console.log(lastNames);
console.log("Note that it gets John Steven Murphy wrong, see answer text for details.");
<ul>
  <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>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>