Subin
Subin

Reputation: 3563

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.

Upvotes: 78

Views: 185163

Answers (26)

EliuX
EliuX

Reputation: 12625

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á-úñü]+){1,2}\s)|(?:(?:[aeodlsz]{1,3}[ ]){0,2}[A-ZÁ-ÚÑÜ][a-zá-úñü]+)/gms) || [];

            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.

---- Update 04-2024 ------------------------

I verified this answer I gave 8 years ago and I made a noticeable change for a nicer code, better regexp and more nuanced response (adds middle-name):

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

  if (fullName.length > 0) {
    var nameTokens = fullName.match(/(?:(?:[A-ZÁ-ÚÑÜ][a-zá-úñü]+){1,2})|(?:(?:[aeodlsz]{1,3}[ ]){0,2}[A-ZÁ-ÚÑÜ][a-zá-úñü]+)/gms) || [];

    switch (nameTokens.length) {
      case 1:
        [result.name] = nameTokens;
        break;
      case 2:
        [result.name, result.lastName] = nameTokens;
        break;
      case 3:
        [result.name, result.lastName, result.secondLastName] = nameTokens;
        break;
      default:
        [result.name, result.middleName, result.lastName, result.secondLastName] = nameTokens;
    }
  }

  return result;
}


console.log(parseName("Marianela")); // A simple name
console.log(parseName("Peña Ávalos")); // Special characters (á) - Last name with two parts
console.log(parseName("Juan Felipe Hernández Borbón")); // A fully structured name
console.log(parseName("Sofía de las Mercedes y Grecia")); // Complex last name with conjunctions ("de las", "y")
console.log(parseName("Jorge Luis Borges-Acevedo")); // Double-barreled last name ("Borges-Acevedo")
console.log(parseName("María del Pilar Díaz")); // "del" as prefix of the last name
console.log(parseName("Xóchitl Sánchez")); // "X" prefix (rare but exists)

Note: This is a case sensitive regexp. If you want it to support last names with upcases just add the i flag to make it insensitive. For instance, change from /gms to /gmis.

Upvotes: 28

abrar
abrar

Reputation: 21

This function will break any name into first name and last name storing the last word as the last name and everything else as the first name. It returns an object which contains the separated names:

function parseName(fullName) {
  const name = fullName.split(' ')
  const person = {}
  if (name.length > 1) {
    person.lastName = name.pop()
    person.firstName = name.join(' ')
  } else {
    person.lastName = ""
    person.firstName = obj.name
  }
  return person
}

console.log(parseName("Ashak Zahin Hasan"))
// { firstName: "Ashak Zahin", lastName: "Hasan" }

Upvotes: 1

Sondre Ljovshin
Sondre Ljovshin

Reputation: 114

There are many ways to Archive this.

I think the easiest way is to split and pop the last name.

let fullname = 'Paul Steve Panakkal'; // from php

let tmpArray = fullname.split(' '); //split the name to an array

const lastname = tmpArray.pop(); // pop the last element of the aray and store it in "lastname" variable
const firstname = tmpArray.join(' '); // join the array to make first and middlename and store it in "firstname" variale

console.log("firstname:", firstname)
console.log("lastname:", lastname)

Upvotes: 3

Aloiso Gomes
Aloiso Gomes

Reputation: 830

Objects can do the Trick with a simple function:

    const fullName = "Edgar Allan Poe"

    const formatter = (name) => {

        const splitedName = name.trim().split(' ')

        if(splitedName.length === 0) return ""

        //here happens the hack!, it prevents duplicate names
        //JS objects overrides duplicate keys, very useful here 
        const output = {
            [splitedName[0]]: splitedName[0],
            //storing first key

            [splitedName[splitedName.length - 1]]: splitedName[splitedName.length - 1] 
            //storing last key (whose may be first key)
        }

        return Object.keys(output).join(' ').trim()
        //now convert object keys into a string. "E pronto rs"

    }

    console.log(formatter(fullName)) // "Edgar Poe"
    console.log(formatter("Elias")) // "Elias"
    console.log(formatter("")) // ""

Upvotes: 0

Pavlo Zhuravlov
Pavlo Zhuravlov

Reputation: 373

The most common solution, where we always take the first word for the first name and the rest for the last name:

const splitName = (name = '') => {
  const [firstName, ...lastName] = name.split(' ').filter(Boolean);
  return {
    firstName: firstName,
    lastName: lastName.join(' ')
  }
}

console.log(splitName('Jon  Snow'));

console.log(splitName(' Jon '));

console.log(splitName(' Jon The    White Wolf '));

Upvotes: 17

shayank
shayank

Reputation: 86

If you want the last name to be all the names after the first name:

function splitFirstLast(name) {
  return {
    firstName: name.indexOf(' ') !== -1 && name.substring(0, name.indexOf(' ')) || name,
    lastName: name.indexOf(' ') !== -1 && name.substring(name.indexOf(' ') + 1) || ''
  }
}

Upvotes: 0

Penny Liu
Penny Liu

Reputation: 17398

Another alternative could be using regular expression.

\w+\s\w+(?=\s)|\w+

The above regex will find firstName and lastName string pattern which matches two or three combinations of naming types.

const regex = /\w+\s\w+(?=\s)|\w+/g;

const name1 = 'Paul Steve Panakkal';
const [firstName1, lastName1] = name1.trim().match(regex);
console.log(`${firstName1} | ${lastName1}`);

const name2 = 'John Doe';
const [firstName2, lastName2] = name2.trim().match(regex);
console.log(`${firstName2} | ${lastName2}`);

Details

  • \w+ Match any word character.
  • ?=\s Match any whitespace character but not catching it.

Upvotes: 1

water
water

Reputation: 35

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

You should add trim() just in case the user accidentally types an extra whitespace!

Upvotes: 0

Chung Nguyen
Chung Nguyen

Reputation: 501

Use the following code, it works for me

let name = "Paul Steve Panakkal"
let parts = name.split(' ')
let firstName = parts.shift();  // Paul
let lastName = parts.join(' '); // Steve Panakkal

console.log({
firstName,
lastName
})

Upvotes: 5

karser
karser

Reputation: 1693

I came up with this logic:

const fullName = "Paul Steve Panakkal";
const idx = fullName.lastIndexOf(' ');
const firstName = idx !== -1 ? fullName.substring(0, idx) : fullName;
const lastName = idx !== -1 ? fullName.substring(idx + 1) : '';
console.log('firstName:', firstName, 'lastName:', lastName);

output:

firstName: Paul Steve lastName: Panakkal

Upvotes: 0

Danil Speransky
Danil Speransky

Reputation: 30453

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

Upvotes: 171

gauravds
gauravds

Reputation: 3011

const fullName = 'Paul Steve Panakkal'.split(' ');
const lastName = fullName.pop(); // 'Panakkal'
const firstName = fullName.join(' '); // 'Paul Steve'
console.log(firstName);
console.log(lastName);

Upvotes: 2

Josh
Josh

Reputation: 1

var fullName = "Paul Steve Panakkal";

You can use the split function to split the full name then the result like displaying elements in an array or list.

This is what happens when you use the split function.

fullName.split(" ")

["Paul", "Steve", "Panakkal"]

This is not saved to any variable. You can perform the split function and assign an element to a well defined variable like this.

var firstName = fullName.split(" ")[0];

var lastName = fullName.split(" ")[1];

var otherName = fullName.split(" ")[2];

Upvotes: 0

Philippe Genois
Philippe Genois

Reputation: 639

This way, both firstName and lastName are always correct

var names = fullName.split(' ');
if (!names || names.length <= 1) {
   firstName = this.name;
   lastName = '';
} else {
   firstName = names.slice(0, -1).join(' ');
   lastName = names.slice(-1).join(' ');
}

Upvotes: 0

Marcelo Batemarchi
Marcelo Batemarchi

Reputation: 31

If you mean the last name is all the names after the first name, just use:

var name = "Paul Steve Panakkal";
var arrName = name.split(" ");
var firstName = arrName.slice(0, 1).join(' ');
var lastName = arrName.slice(1, arrName.length).join(' ');

Upvotes: 0

Akash Jain
Akash Jain

Reputation: 1052

I tried below code and it works cool for me

var full_name = 'xyz abc pqr';
var name = full_name.split(' ');
var first_name = name[0];
var last_name = full_name.substring(name[0].length.trim());

In above example:

(1)

If full_name = 'xyz abc pqr';
first_name = "xyz";
last_name = "abc pqr";

(2)

If `full_name = "abc"`:
Then first_name = "abc";
and last_name = "";

Upvotes: 4

Marius
Marius

Reputation: 1759

A comenter said What if want first name to be "Paul" and last name "Steve Panakkal"

var name = "Paul Steve Panakkal" // try "Paul", "Paul Steve"
var first_name = name.split(' ')[0]
var last_name = name.substring(first_name.length).trim()
console.log(first_name)
console.log(last_name)

Upvotes: 4

Hasan Tuna Oru&#231;
Hasan Tuna Oru&#231;

Reputation: 1896

var firstName = fullName.split(" ")[0];

Upvotes: 1

Nick Schwab
Nick Schwab

Reputation: 31

Watch out for edge-cases like only a first name being provided or two or more spaces being entered. If you only want to parse out the first and last name, this will do the trick (full name should always contain at least 1 character to avoid first_name being set to an empty string):

var full_name_split = "Paul Steve Panakkal".split(" ");
var first_name = full_name_split[0];
var last_name = full_name_split.length > 1 ? full_name_split[full_name_split.length - 1] : null;

Upvotes: 3

nonkertompf
nonkertompf

Reputation: 397

You needn't use any split method and create unnecessary arrays for that operation. Just use lastIndexOf and substring methods of javascript.

var s = "Paul Steve Panakkal";
var a = s.lastIndexOf(' '); // last occurence of space
var b = s.substring(0, a); // Paul Steve
var c = s.substring(a+1); // Panakkal

Upvotes: 2

Yanir Calisar
Yanir Calisar

Reputation: 475

Use this code:

You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.


function splitFullName(a,b,c){
    String.prototype.capitalize = function(){
        return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
    };
    document.getElementById(c).oninput=function(){
        fullName = document.getElementById(c).value;
        if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
            first = fullName.capitalize();;
            last = "null";
        }else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
            first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
            last = fullName.substring(first.length +1,fullName.length).capitalize();
        }else{
            first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
            last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
        }
        document.getElementById(a).value = first;
        document.getElementById(b).value = last;
    };
    //Initial Values
    if(document.getElementById(c).value.length === 0){
        first = document.getElementById(a).value.capitalize();
        last = document.getElementById(b).value.capitalize();
        fullName =  first + " " + last ;
        console.log(fullName);
        document.getElementById(c).value = fullName;
    }
}

//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");

Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/

Upvotes: 2

blak3r
blak3r

Reputation: 16516

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

Upvotes: 4

Visual Micro
Visual Micro

Reputation: 1561

if you assume the last word is the last name and a single word name is also a last name then ...

var items = theName.split(' '),
    lastName = items[items.length-1],
    firstName = "";

for (var i = 0; i < items.length - 1; i++) {
   if (i > 0) {
      firstName += ' ';
   }
   firstName += items[i];
}

Upvotes: 3

abuduba
abuduba

Reputation: 5042

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

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

Upvotes: 16

techie_28
techie_28

Reputation: 2133

use JS split with space as delimitter.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

Yes:

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

References:

Upvotes: 48

Related Questions