Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex, split user's full name

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?

like image 340
Ilya Avatar asked Oct 24 '12 08:10

Ilya


1 Answers

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 = "";
like image 142
dfsq Avatar answered Nov 15 '22 21:11

dfsq