adasdasd adasdasd - 15 days ago 5
Javascript Question

Get all string in one variable after space in javascript

what i am doing

for example i have a name



var nameofuser = 'John Constantine vayo';
var values = nameofuser.split(" ");
var f_name = values[0];
var l_name = nameofuser.substr(nameofuser.indexOf(' ') + 1);
console.log(f_name);
console.log(l_name);





it is working fine when user entering his last name and other title or so on, it is all going in l_name but when a user enterned only first name like only 'John' then l_name is also populated with 'john' :(,

i want IF a user type last name and so on then only l_name should be populated.

if user type only first name then only f_name with first name should be populated

Answer
var nameofuser = 'John Constantine vayo';
var values = nameofuser.split(" ");
var f_name = values[0];
var l_name = values[1] ? nameofuser.substr(nameofuser.indexOf(' ') + 1) : '';
console.log(f_name);
console.log(l_name);