Split First name and Last name using JavaScript

123,451

Solution 1

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

Solution 2

Yes:

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

References:

Solution 3

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.

Solution 4

I think, it's time to get started with regular expressions :)

"Paul Steve Panakkal".split(/(\s).+\s/).join("") // "Paul Panakkal"

Solution 5

Extended version of Speransky Danil's answer which handles the case where the supplied string has only one word in it.

/**
 * Gets the first name, technically gets all words leading up to the last
 * Example: "Blake Robertson" --> "Blake"
 * Example: "Blake Andrew Robertson" --> "Blake Andrew"
 * Example: "Blake" --> "Blake"
 * @param str
 * @returns {*}
 */
exports.getFirstName = function(str) {
    var arr = str.split(' ');
    if( arr.length === 1 ) {
        return arr[0];
    }
    return arr.slice(0, -1).join(' '); // returns "Paul Steve"
}

/**
 * Gets the last name (e.g. the last word in the supplied string)
 * Example: "Blake Robertson" --> "Robertson"
 * Example: "Blake Andrew Robertson" --> "Robertson"
 * Example: "Blake" --> "<None>"
 * @param str
 * @param {string} [ifNone] optional default value if there is not last name, defaults to "<None>"
 * @returns {string}
 */
exports.getLastName = function(str, ifNone) {
    var arr = str.split(' ');
    if(arr.length === 1) {
        return ifNone || "<None>";
    }
    return arr.slice(-1).join(' ');
}
Share:
123,451
Subin
Author by

Subin

Contact : [email protected] GitHub : https://github.com/subins2000 Twitter : https://twitter.com/SubinSiby Facebook : http://fb.com/SubinSiby Google + : http://google.com/+SubinSiby I am a teen Programmer, Blogger, Web Developer and a student. I like to create new things and help people. My favorite languages are PHP, Python and JavaScript with jQuery. I love working with FOSSs.

Updated on November 17, 2021

Comments

  • Subin
    Subin over 2 years

    I have a user with the name Paul Steve Panakkal. It's a long name it won't fit to the div container. So is there anyway to split first name and last name from it using JavaScript or jQuery?

    The name is got from PHP into a variable in JavaScript. This is then splitted using JS.

  • Hengjie
    Hengjie almost 10 years
    The problem with .split(" ").slice(0, -1).join(' ') for first name is that if the string only contains one letter, it fails to give the first name.
  • Leandro Faria
    Leandro Faria about 9 years
    Using your method first name would be "Paul Steve" and last name "Panakkal". What if want first name to be "Paul" and last name "Steve Panakkal" -- which means last name would be everything after the first white space. How to do it?
  • Michael
    Michael almost 8 years
    If you only put in "Paul" as the full name, it will use Paul as the first and last name...
  • Lalit
    Lalit about 7 years
    Also how would this solution work if they have two (highly likely) or four names (not so much)?
  • David Ortiz
    David Ortiz about 6 years
    It should be full_name.substring(name[0].length).trim(); with the trim function at the end
  • lsimonetti
    lsimonetti almost 6 years
    In addition, what happens if there's a leading white space? It would be a good idea to "trim" the strings before splitting/slicing them.. like so str.replace(/\s+/g, '')
  • itsdarrylnorris
    itsdarrylnorris over 5 years
    This will work fine as long you are not supporting Spanish names.
  • abuduba
    abuduba over 5 years
    @darol100 Could you post any example please?
  • itsdarrylnorris
    itsdarrylnorris over 5 years
    Spanish name has two last names. My name is a great example: "Darryl Norris Marquez".split(/(\s).+\s/).join("") // "Darryl Marquez", which is not right. Norris Marquez is my last name. However, I do not think there is a good way to identify a Spanish last name VS a middle name. See @EliuX for more details on how to support Spanish last name.
  • CoderUni
    CoderUni over 3 years
    could you explain what your whole code does? You've only explained that trim() removes any leading and trailing whitespace
  • Grant
    Grant over 2 years
    This is the best answer.