Split First name and Last name using JavaScript

In Spanish it can be tricky because you may have a second optional name and even complex surnames like "del Bosque" or "de la Hoya", vowels with accent marks and the ñ. The following javascript is capabable of parsing a full spanish name, having in count you are writting it respecting the upper and lower cases. It will return a json giving you

  1. name: 1 or 2 main names
  2. lastName: the main lastname
  3. secondLastName: The second lastname

The code is:

function parseName(input) {
        var fullName = input || "";
        var result = {};

        if (fullName.length > 0) {
            var nameTokens = fullName.match(/[A-ZÁ-ÚÑÜ][a-zá-úñü]+|([aeodlsz]+\s+)+[A-ZÁ-ÚÑÜ][a-zá-úñü]+/g) || [];

            if (nameTokens.length > 3) {
                result.name = nameTokens.slice(0, 2).join(' ');
            } else {
                result.name = nameTokens.slice(0, 1).join(' ');
            }

            if (nameTokens.length > 2) {
                result.lastName = nameTokens.slice(-2, -1).join(' ');
                result.secondLastName = nameTokens.slice(-1).join(' ');
            } else {
                result.lastName = nameTokens.slice(-1).join(' ');
                result.secondLastName = "";
            }
        }

        return result;
}

The surnames are required if you are going to specify a second name. Try it out with:

  • Vicente Hernández Planes
  • Oscar de la Hoya
  • José Julian Martí Pérez
  • Manuel de Céspedes del Castillo
  • Calixto García Íñiguez

Even try out a complex one like

  • María de la Caridad del Bosque y Loynáz

Comment your experiences with it.


Yes:

var fullName = "Paul Steve Panakkal".split(' '),
    firstName = fullName[0],
    lastName = fullName[fullName.length - 1];

References:

  • string.split().

You should use the String.prototype.split() method:

'Paul Steve Panakkal'.split(' '); // returns ["Paul", "Steve", "Panakkal"]

You can use it this way:

'Paul Steve Panakkal'.split(' ').slice(0, -1).join(' '); // returns "Paul Steve"
'Paul Steve Panakkal'.split(' ').slice(-1).join(' '); // returns "Panakkal"

So in common:

var firstName = fullName.split(' ').slice(0, -1).join(' ');
var lastName = fullName.split(' ').slice(-1).join(' ');