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
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
Share Improve this question asked Oct 7, 2014 at 4:32 Vishnu PrasadVishnu Prasad 7271 gold badge11 silver badges28 bronze badges7 Answers
Reset to default 13You 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];
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');
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);
http://jsfiddle.net/d1L3vqc5/
var displayname = "abc pqr xyz";
var d = displayname.replace(/\s+\w+\s/g, " ");
console.log(d)
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] );
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(' '));
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];