简体   繁体   中英

How to extract only first and last name by removing the middle name using javascript

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

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];

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)

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(' '));

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] );

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM