Reputation: 727
I am trying to display only First and Last name. Sometimes there will be a middle name comes. In that case i need remove the middle name and join first and last name.How is it possible using JavaScript. The name comes to a variable from database like
var displayname="abc pqr xyz"
i just need "abc xyz" to a variable . Thanks in advance
Upvotes: 3
Views: 8156
Reputation: 57
To only get the first name and last name you can first .split
the string by the space so it turns into an array. And then you get the first and last name and add it together.
const displayname = "abc pqr xyz";
const splitDisplayName = displayname.split(" ");
const newDisplayName = splitDisplayName[0] + " " + splitDisplayName[2];
Upvotes: 0
Reputation: 1
var displayname = "abc pqr xyz";
var d = displayname.replace(/\s+\w+\s/g, " ");
console.log(d)
Upvotes: 1
Reputation: 2828
Just throwing in another regular expression answer, which I think would have less overhead than splitting. This will work for any number--including zero--of middle names.
var name = "abc def ghi jkl";
var re = /^(\w+ ).*?(\w+)$/;
name.search(re);
alert(RegExp.$1 + " " + RegExp.$2);
Upvotes: 1
Reputation: 309891
You can use a regular expression keeping only the 1st and 3rd groups ...
var displayname = "abc pqr xyz";
var newname = displayname.replace(/(\w+\s+)(\w+\s+)(\w+)/, '$1$3');
Upvotes: 2
Reputation: 16214
In case if first name consists of a two or more words (like 'Anna Maria Middle_Name Last_Name')...
var displayname = "abc pqr xyz";
var tmp = displayname.split(/\s+/);
if (tmp.length > 2)
tmp.splice(-2, 1);
alert(tmp.join(' '));
Upvotes: 0
Reputation: 2654
You can use split()
method and take the first and last array element
var displayname="abc pqr xyz";
var result = displayname.split(" ");
alert( result[0]+" "+ result[2] );
Upvotes: 0
Reputation: 10572
You could split on white space and take the first and last element of the array.
var displayname = "abc pqr xyz";
var tmp = displayname.split(" ");
displayname = tmp[0] + " " + tmp[tmp.length-1];
Upvotes: 13