Skip to content Skip to sidebar Skip to footer

Javascript Regular Expression To Attempt To Split Name Into Title/first Name(s)/last Name

I want to try and detect the different parts of a person's name in Javascript, and cut them out so that I can pass them onto something else. Names can appear in any format - for ex

Solution 1:

Why not split() and just check the resulting parts:

// Split on each space charactervar name = "Miss Victoria C J Long".split(" ");

// Check the first part for a title/prefixif (/^(?:Dr|Mr|Mrs|Miss|Master|etc)\.?$/.test(name[0])) {
    name.shift();
}

// Now you can access each part of the name as an arrayconsole.log(name);
//-> Victoria,C,J,Long

Working Demo: http://jsfiddle.net/AndyE/p9ra4/

Of course, this won't work around those other issues people have mentioned in the comments, but you'd struggle on those issues even more with a single regex.

Solution 2:

var title = '';
var first_name = '';
var last_name = '';
var has_title = false;

if (name != null)
{
    var new_name = name.split(" ");

    // Check the first part for a title/prefixif (/^(?:Dr|Mr|Mrs|Miss|Master)\.?$/i.test(new_name[0]))
    {
        title = new_name.shift();
        has_title = true;
    }
    if (new_name.length > 1)
    {
        last_name = new_name.pop();
        first_name = new_name.join(" ");
    }
    elseif(has_title)
    {
        last_name = new_name.pop();
    }
    else
    {
        first_name = new_name.pop();
    }
}

Adapted from Accepted Answer :)

Post a Comment for "Javascript Regular Expression To Attempt To Split Name Into Title/first Name(s)/last Name"