javascript regex, split user's full name

javascript, regex

Solution

Use split + shift methods.

var parts = "Thomas Mann".split(" "),
    first = parts.shift(),
    last = parts.shift() || "";

So in case of single word name it will give you expected result:

last = "";

Problem

I have user's firstname and lastname in one string, with space between e.g. `John Doe` `Peter Smithon` And now I want convert this string to two string - firstname and lastname `John Doe` -> first = `John`, last = `Doe` `John` -> first = `John`, last = "" `[space]Doe` -> first = "", last = `Doe`. I am using next code ``` var fullname = "john Doe" var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe ``` and this works well for two-word fullname. But if fullname has one word, then I have problem ``` var fullname = "john" var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john ``` http://jsfiddle.net/YyCKx/ any ideas?

Original source