使用JS获取名称首字母

时间:2015-10-12 08:09:16

标签: javascript jquery

我的要求是将姓名缩写为

#define __USE_XOPEN2K

我可以使用此结果获得上述结果,

Name = FirstName LastName 

Initials =  FL

但现在我的要求被更改,好像名称只包含1个字或更多2个字,因此在下列情况下,我如何根据我的要求获得缩写,

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

如何从JS中的字符串获取上述内容?

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

24 个答案:

答案 0 :(得分:33)

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



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




答案 1 :(得分:19)

您可以使用此速记js

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

要获得名字和姓氏,您可以使用此简写功能

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

答案 2 :(得分:18)

检查以下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'));




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

names = string.split(' '),

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

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

如果有多个名称,则需要姓氏的第一个字母(位置names.length - 1中的一个):

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

答案 3 :(得分:5)

您使用以下一行逻辑:

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

答案 4 :(得分:5)

最短的班轮:

获取第一个和最后一个名字首字母:John Doe Smith => JS

name.match(/(\b\S)?/g).join("").match(/(^\S|\S$)?/g).join("").toUpperCase()

获取所有首字母缩写:"John Doe Smith" => "JDS"

name.match(/(\b\S)?/g).join("").toUpperCase()

获取第一个和最后一个,除非只有第一个,否则获取第一个2。 (OP的问题)

John => JO"John Doe Smith" => "JS"

name.match(/(^\S\S?|\b\S)?/g).join("").match(/(^\S|\S$)?/g).join("").toUpperCase()

注意:如果名称包含,或其他非文字字符,则可以使用/w代替/S或对其进行预先消毒

答案 5 :(得分:4)

你可以为此做一个功能:

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;

}

小提琴:http://localhost:8080/SpringService/service/laporan/laporanoutstanding/2015-08-01/2015-08-29

答案 6 :(得分:4)

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

答案 7 :(得分:3)

令人惊讶的是,没有一个答案能很好地利用 reduce

使用 Array.reduce(),您可以执行以下操作 -

const getInitials = (fullName) => {
  const allNames = fullName.trim().split(' ');
  const initials = allNames.reduce((acc, curr, index) => {
    if(index === 0 || index === allNames.length - 1){
      acc = `${acc}${curr.charAt(0).toUpperCase()}`;
    }
    return acc;
  }, '');
  return initials;
}

运行下面的代码片段以检查不同用例的首字母-

const testNames = [
  'Albus Percival Wulfric Brian dumbledore',
  'Harry Potter',  
  'Ron',
  '',
  'Çigkofte With Érnie',
  'Hermione ',
  'Neville LongBottom '
]

const getInitials = (fullName) => {
  const allNames = fullName.trim().split(' ');
  const initials = allNames.reduce((acc, curr, index) => {
    if(index === 0 || index === allNames.length - 1){
      acc = `${acc}${curr.charAt(0).toUpperCase()}`;
    }
    return acc;
  }, '');
  return initials;
}


console.log(testNames.map(getInitials));

注意:这是一种广泛用于在头像中显示姓名的情况,您不希望名字的首字母重复两次,并且希望将首字母限制为最多 2 个字母

答案 8 :(得分:2)

使用地图功能更轻松:

var name = "First Last";
var initials = Array.prototype.map.call(name.split(" "), function(x){ return x.substring(0,1).toUpperCase();}).join('');

答案 9 :(得分:1)

  

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

由于您的全名中可以包含任意数量的单词(中间名),所以最好的选择是将其吐入一个数组中,并从该数组中的第一个单词和最后一个单词中获取初始字符,然后一起返回字母。

如果您的“全名”仅包含一个单词,则array[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)}`;
}

样本输出:

> nameToInitials('Prince') //“ P”

> nameToInitials('FirstName LastName') //“ FL”

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

答案 10 :(得分:1)

此解决方案使用数组功能,箭头功能和三元运算符在一行中实现目标。 如果名称是单个单词,则只使用前两个字符,如果更多,则使用名字和姓氏的第一个字符。 (感谢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()

答案 11 :(得分:0)

我今天需要它作为我的 React 代码中的方法。我从状态中获取用户名作为道具。之后,我只是在组件的 props 中传递了我的方法。

getUserInitials() {
  const fullName = this.props.user.name.split(' ');
  const initials = fullName.shift().charAt(0) + fullName.pop().charAt(0);
  return initials.toUpperCase();
 }

答案 12 :(得分:0)

使用 ES6 Destructering 的简便方法:

const getInitials = string =>
  string
    .split(' ')
    .map(([firstLetter]) => firstLetter)
    .filter((_, index, array) => index === 0 || index === array.length - 1)
    .join('')
    .toUpperCase();

答案 13 :(得分:0)

另一种相同的方法。

function getInitials(str) {
  const FirstName = str.split(' ')[0];
  const LastName = str.split(' ').reduceRight(a => a);

  // Extract the first two characters of a string
  if (FirstName === LastName) {
    return FirstName.trim()
      .substring(0, 2)
      .toUpperCase();
  }

  // Abbreviate FirstName and LastName
  return initials = [FirstName, LastName]
    .map(name => name[0])
    .join('').toUpperCase();
}

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

答案 14 :(得分:0)

使用initials,它可以处理大多数情况,并涵盖了名称的所有参量。

要查看访问方式,请尝试在https://github.com/gr2m/initials上添加您的姓名

谢谢

答案 15 :(得分:0)

要获取名字和姓氏的缩写,请尝试使用下面的功能。

const getInitials = string => {
    const names = string.split(' ');
    const initials = names.map(name => name.charAt(0).toUpperCase())
    if (initials.length > 1) {
        return `${initials[0]}${initials[initials.length - 1]}`;
    } else {
        return initials[0];
    }
};
console.log(getInitials("1stName 2ndName 3rdName 4thName 5thName")); // 15
console.log(getInitials("FirstName MiddleName LastName")); // FL

发生的事情:该函数拆分传入的字符串,忽略名字和姓氏之间的任何名称,并返回其首字母缩写。如果输入单个名称,则返回单个首字母。我希望这会有所帮助,加油。

答案 16 :(得分:0)

我看到了很多过于复杂的方法。 我真的更想尽可能简化事物,并使用合成或咖喱来增强事物。

这是我的2美分:


// Helpers

const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const reverseText = (text = '')=> text.split('').reverse().join('');

const getInitialsDelimitBy = (delimiter = ' ') => (displayName = '') =>
  displayName
    .trim()
    .split(delimiter)
    .reduce((acc, value) => `${acc}${value.charAt(0)}`, '')
    .toUpperCase();

const getInitialsDelimitByComas = pipe(
  getInitialsDelimitBy(','), 
  reverseText
);

const getInitialsDelimitBySpaces = getInitialsDelimitBy(' '); // Not necessary because of the default but clearer 

const comaInitials = getInitialsDelimitByComas('Wayne, Bruce') // BW
const spaceInitials = getInitialsDelimitBySpaces('Bruce Wayne') // BW

对于您的具体情况,我建议如下:

const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);

const nameProcessor = {
  single: (name = '') =>
    name
      .trim()
      .substring(0, 2)
      .toUpperCase(),
  multiple: pipe(
    name => name.trim().split(' '),
    words => `${words[0].charAt(0)}${words[words.length - 1].charAt(0)}`,
    initials => initials.toUpperCase(),
  ),
};

const getInitials = (displayName = '') => 
  displayName.split(' ').length === 1 
    ? nameProcessor.single(displayName) 
    : nameProcessor.multiple(displayName)

getInitials('FullName') // FU
getInitials('FirstName MiddleName LastName') // FL
getInitials('1stName 2ndName 3rdName 4thName 5thName') // 15

我希望可以帮助= D

答案 17 :(得分:0)

这应该适用于大多数情况,包括中间名和名字(@njmwas答案的扩展名)。

const initialArr = name.split(" ").map((n)=>n[0]);
const init = (initialArr.length > 1)? `${initialArr[0]}${initialArr[initialArr.length - 1]}` : initialArr[0];
const initials = init.toUpperCase();

答案 18 :(得分:0)

var personName = "FirstName MiddleName LastName";
var userArray = personName.split(" ");
var initials = [];
if(userArray.length == 1){
 initials.push(userArray[0][0].toUpperCase() + userArray[0][1]).toUpperCase();}
else if(userArray.length > 1){
initials.push(userArray[0][0].toUpperCase() + userArray[userArray.length-1][0].toUpperCase());}
console.log(initials);

答案 19 :(得分:0)

使用一些es6功能:

const testNameString = 'Hello World';
const testNameStringWeird = 'Hello  darkness My  - Óld Friend Nikolaus Koster-Walder ';
const getInitials = nameString =>{
       const regexChar = /\D\w+/
       return nameString
        .trim() //remove trailing spaces
        .split(' ') // splits on spaces
        .filter(word => word.length > 0) // strip out double spaces
        .filter(word => regexChar.test(word)) // strip out special characters
        .map(word => word.substring(0, 1).toUpperCase()) // take first letter from each word and put into array
}
console.log('name:',testNameString,'\n initials:',getInitials(testNameString));
console.log('name:',testNameStringWeird,'\n initials:',getInitials(testNameStringWeird));

答案 20 :(得分:0)

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

答案 21 :(得分:0)

您可以执行以下操作;

export default class App extends Vue{
 data() {
    return {
      evidence: 0
    }
 },
 methods: {
  handleFileSelect(evt: any) {
      var evidence = this.evidence;
  }
 }
};

然后可以像这样使用该功能;

    function initials(name){

      //splits words to array
      var nameArray = name.split(" ");

      var initials = '';

      //if it's a single word, return 1st and 2nd character
      if(nameArray.length === 1) {
        return nameArray[0].charAt(0) + "" +nameArray[0].charAt(1);
      }else{
         initials = nameArray[0].charAt(0);
      }
      //else it's more than one, concat the initials in a loop
      //we've gotten the first word, get the initial of the last word


      //first word
      for (i = (nameArray.length - 1); i < nameArray.length; i++){
        initials += nameArray[i].charAt(0);
      }
     //return capitalized initials
     return initials.toUpperCase();
   }

我希望这会有所帮助。

答案 22 :(得分:0)

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

答案 23 :(得分:0)

仅更新了Andrea的版本:

var getInitials = function (string) {
   var initials = "";
   var names = string.split(' ');
   for (n = 0; n < names.length; n++) {
        initials += names[n].substring(0, 1).toUpperCase();
    }
    return initials;
};

如果字符串包含姓氏,只需将 names.length 更改为 names.length-1 以忽略姓氏

相关问题