Search code examples
javascriptstringparsing

Split First name and Last name using JavaScript


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.


Solution

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