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 lastnameJohn 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?
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 = "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With