最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to extract only first and last name by removing the middle name using javascript - Stack Overflow

programmeradmin8浏览0评论

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 badges
Add a comment  | 

7 Answers 7

Reset to default 13

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)

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];
发布评论

评论列表(0)

  1. 暂无评论