Javascript 使用 JS 获取姓名缩写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33076177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:35:52  来源:igfitidea点击:

Getting Name initials using JS

javascriptjquery

提问by Mathematics

My requirement were to get name initials as,

我的要求是获得姓名首字母,

Name = FirstName LastName 

Initials =  FL

I can get above result using this,

我可以使用这个得到以上结果,

var initials = item.FirstName.charAt(0).toUpperCase() + 
                                   item.LastName.charAt(0).toUpperCase();

But now my requirements are changed as if name only consist of 1 word or more then 2, so in following cases how can I get initials as per my requirements,

但是现在我的要求发生了变化,好像名称只包含 1 个或更多然后 2 个单词,因此在以下情况下,我如何根据我的要求获得首字母缩写,

FullName =  FU

FirstName MiddleName LastName = FL

1stName 2ndName 3rdName 4thName 5thName = 15

How can I get above intials from strings in JS ?

我怎样才能从 JS 中的字符串中获得上面的缩写?

Also now I only have item.Name string coming in....

另外现在我只有 item.Name 字符串进来......

回答by Shanoor

Why no love for regex?

为什么不喜欢正则表达式?

var name = 'Foo Bar 1Name too Long';
var initials = name.match(/\b\w/g) || [];
initials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
console.log(initials);

回答by njmwas

You can use this shorthand js

你可以使用这个简写js

"FirstName LastName".split(" ").map((n)=>n[0]).join(".");

To get only First name and Last name you can use this shorthand function

要仅获取名字和姓氏,您可以使用此速记函数

(fullname=>fullname.map((n, i)=>(i==0||i==fullname.length-1)&&n[0]).filter(n=>n).join(""))
("FirstName MiddleName OtherName LastName".split(" "));

回答by Andrea

Check the getInitialsfunction below:

检查以下getInitials功能:

var getInitials = function (string) {
    var names = string.split(' '),
        initials = names[0].substring(0, 1).toUpperCase();
    
    if (names.length > 1) {
        initials += names[names.length - 1].substring(0, 1).toUpperCase();
    }
    return initials;
};

console.log(getInitials('FirstName LastName'));
console.log(getInitials('FirstName MiddleName LastName'));
console.log(getInitials('1stName 2ndName 3rdName 4thName 5thName'));

The functions split the input string by spaces:

这些函数用空格分割输入字符串:

names = string.split(' '),

Then get the first name, and get the first letter:

然后获取名字,并获取第一个字母:

initials = names[0].substring(0, 1).toUpperCase();

If there are more then one name, it takes the first letter of the last name (the one in position names.length - 1):

如果有多个名字,则取姓氏的第一个字母(在 position 中的那个names.length - 1):

if (names.length > 1) {
    initials += names[names.length - 1].substring(0, 1).toUpperCase();
}

回答by Yuvraj Chauhan

You use below one line logic:

您使用以下一行逻辑:

"FirstName MiddleName LastName".split(" ").map((n,i,a)=> i === 0 || i+1 === a.length ? n[0] : null).join("");

回答by guramidev

You can do a function for that:

您可以为此执行一个功能:

var name = 'Name';

function getInitials( name,delimeter ) {

    if( name ) {

        var array = name.split( delimeter );

        switch ( array.length ) {

            case 1:
                return array[0].charAt(0).toUpperCase();
                break;
            default:
                return array[0].charAt(0).toUpperCase() + array[ array.length -1 ].charAt(0).toUpperCase();
        }

    }

    return false;

}

Fiddle: http://jsfiddle.net/5v3n2f95/1/

小提琴:http: //jsfiddle.net/5v3n2f95/1/

回答by Aniket

'Aniket Kumar Agrawal'.split(' ').map(x => x.charAt(0)).join('').substr(0, 2).toUpperCase()

回答by deejayy

const getInitials = name => name
  .replace(/[^A-Za-z0-9à-? ]/ig, '')        // taking care of accented characters as well
  .replace(/ +/ig, ' ')                     // replace multiple spaces to one
  .split(/ /)                               // break the name into parts
  .reduce((acc, item) => acc + item[0], '') // assemble an abbreviation from the parts
  .concat(name.substr(1))                   // what if the name consist only one part
  .concat(name)                             // what if the name is only one character
  .substr(0, 2)                             // get the first two characters an initials
  .toUpperCase();                           // uppercase, but you can format it with CSS as well

console.log(getInitials('A'));
console.log(getInitials('Abcd'));
console.log(getInitials('Abcd Efgh'));
console.log(getInitials('Abcd    Efgh    Ijkl'));
console.log(getInitials('Abcd Efgh Ijkl Mnop'));
console.log(getInitials('ábcd éfgh Ijkl Mnop'));
console.log(getInitials('ábcd - éfgh Ijkl Mnop'));
console.log(getInitials('ábcd / # . - , éfgh Ijkl Mnop'));

回答by siwalikm

There are some other answers which solve your query but are slightly complicated. Here's a more readable solution which covers most edge cases.

还有一些其他答案可以解决您的查询,但稍微复杂一些。这是一个更具可读性的解决方案,它涵盖了大多数边缘情况。

As your full name can have any number of words(middle names) in it, our best bet is to spit it into an array and get the initial characters from the first and last words in that array and return the letters together.

由于您的全名可以包含任意数量的单词(中间名),因此我们最好的办法是将其放入一个数组中,并从该数组中的第一个和最后一个单词中获取初始字符,然后将这些字母一起返回。

Also if your 'fullName' contains only one word, word at array[0]and array[array.length - 1]would be the same word, so we are handling that if the first if.

此外,如果您的 'fullName' 仅包含一个单词,则单词 atarray[0]array[array.length - 1]将是同一个单词,因此我们正在处理如果第一个if.

function nameToInitials(fullName) {
  const namesArray = fullName.split(' ');
  if (namesArray.length === 1) return `${namesArray[0].charAt(0)}`;
  else return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`;
}

Sample outputs :

示例输出:

> nameToInitials('Prince')// "P"

> nameToInitials('Prince')// "P"

> nameToInitials('FirstName LastName')// "FL"

> nameToInitials('FirstName LastName')// "FL"

> nameToInitials('1stName 2ndName 3rdName 4thName 5thName')// "15"

> nameToInitials('1stName 2ndName 3rdName 4thName 5thName')// "15"

回答by NMI

let initial = username.match(/\b(\w)/g).join('')

回答by Prabs

This solution uses Array capabilities, Arrow function and ternary operator to achieve the goal in one line. If name is single word, just take first two chars, but if more, then take 1st chars of first and last names. (thanks omn for reminding single word name use case)

该解决方案使用 Array 功能、Arrow 函数和三元运算符在一行中实现目标。如果 name 是单个单词,则只取前两个字符,但如果更多,则取名字和姓氏的第一个字符。(感谢 omn 提醒单个单词名称用例)

string.trim().split(' ').reduce((acc, cur, idx, arr) => acc + (arr.length > 1 ? (idx == 0 || idx == arr.length - 1 ? cur.substring(0, 1) : '') : cur.substring(0, 2)), '').toUpperCase()