source

JS를 사용하여 이름 이니셜 가져오기

manysource 2023. 10. 17. 20:22

JS를 사용하여 이름 이니셜 가져오기

문자열에서 이니셜을 추출하고 싶은데 다음과 같습니다.

Name = FirstName LastName 
Initials =  FL

나는 이것을 이용하여 위의 결과를 얻을 수 있습니다.

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

하지만 지금은 이름이 1단어 또는 2단어 이상으로만 구성된 것처럼 변경되어서, 다음과 같은 경우에는 어떻게 내 요구에 따라 이니셜을 얻을 수 있습니까?

FullName =  FU
FirstName MiddleName LastName = FL
1stName 2ndName 3rdName 4thName 5thName = 15

JS의 문자열에서 위의 이니셜을 얻으려면 어떻게 해야 합니까?

또한 지금은 나만 가지고 있습니다.item.Name문자열을 입력합니다.

왜 regex를 사랑하지 않습니까?

유니코드 문자를 지원하고 ES6 기능을 사용하도록 업데이트됨

let name = 'ÇFoo Bar 1Name too ÉLong';
let rgx = new RegExp(/(\p{L}{1})\p{L}+/, 'gu');

let initials = [...name.matchAll(rgx)] || [];

initials = (
  (initials.shift()?.[1] || '') + (initials.pop()?.[1] || '')
).toUpperCase();

console.log(initials);

이 속기 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(" "));

을 합니다.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();
}

처음 및 마지막 이니셜 가져오기: 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()

국제 버전: "Störfried Würgekloß" => "SW"

name.match(/(^\S\S?|\s\S)?/g).map(v=>v.trim()).join("").match(/(^\S|\S$)?/g).join("").toLocaleUpperCase()

참고: 이름에 다음이 포함된 경우,또는 다른 단어가 아닌 문자를 사용할 수 있습니다./w대신에/S또는 사전에 소독을 합니다.

일반 아바타 사용사례

어떤 답도 잘 활용되지 않았다는 사실에 놀랐을 뿐입니다.

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', // AD
  'Harry Potter',  // HP
  'Ron', // R
  '', // <empty>
  'Çigkofte With Érnie', // ÇÉ
  'Hermione ', // H  (Notice that there is a space after the name) 
  'Neville LongBottom ' // NL (space after name is trimmed)
]

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

메모

This one is for a widely used case for displaying names in Avatars, where you wouldn't want first name initial to be repeated twice and want to restrict the initials to a max of 2 letters

아래의 한 줄 논리를 사용할 수 있습니다.

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

질문을 해결할 수 있지만 약간 복잡한 다른 답변이 있습니다.여기 대부분의 엣지 케이스를 다루는 보다 읽기 쉬운 솔루션이 있습니다.

전체 이름에는 임의의 수의 단어(중간 이름)가 포함될 수 있기 때문에, 우리의 최선의 방법은 그것을 배열에 집어넣고 그 배열의 첫 번째 단어와 마지막 단어의 첫 글자를 가져와서 글자들을 함께 돌려주는 것입니다.

또한 'fullName'에 한 단어만 포함되어 있는 경우에는 다음 단어를 입력합니다.array[0]그리고.array[array.length - 1]같은 단어가 될 것이기 때문에 우리는 만약 첫번째가if.

function nameToInitials(fullName) {
  const namesArray = fullName.trim().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"

let initial = username.match(/\b(\w)/g).join('')
'Aniket Kumar Agrawal'.split(' ').map(x => x.charAt(0)).join('').substr(0, 2).toUpperCase()

다음과 같은 기능을 수행할 수 있습니다.

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/

+ 능률적인
+ 고리 없음
+ 단순 분기(3차 연산자만 해당)
+ 공간이 없는 케이스를 처리합니다(인쇄 2문자)
+ 어레이 메모리 할당 없음(actually 어레이 처리 없음) - 잘라낸 문자열 입력이 필요합니다.

function getInitials(name) {
    const hasTokens = name.indexOf(' ') !== -1
    return name.substring(0, hasTokens ? 1 : 2) + (hasTokens ? name.charAt(name.lastIndexOf(' ') + 1) : '')
}

console.log(getInitials("A B"), 'AB')
console.log(getInitials("Abc Def"), 'AD')
console.log(getInitials("Abc Xyz"), 'AX')
console.log(getInitials("S Xyz"), 'SX')
console.log(getInitials("SXyz "), 'SX')
console.log(getInitials("T30"), 'T3')

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

지도 기능을 통해 보다 용이함:

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

@njmwas의 유사하지만 약간 더 가까운 버전은 다음과 같이 대답했습니다.

let name = 'Fred Smith';
let initials = name.split(' ').reduce((acc, subname) =>
    acc + subname[0], '')
console.log(initials) // FS

또는 축약 점을 포함하려면:

let name = 'Fred Smith';
let initials = name.split(' ').reduce((acc, subname) =>
    acc + subname[0] + '.', '')
console.log(initials) // F.S.

당신은 이와 같은 일을 할 수 있습니다.

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

그런 다음 이 기능을 사용할 수 있습니다.

  var fullname = 'badmos tobi';
  initials(fullname); //returns BT 

  var surname = 'badmos';
  initials(surname); //returns BA

  var more = 'badmos gbenga mike wale';
  initials(more); //returns BW;

도움이 되었으면 좋겠습니다.

이 솔루션은 Array 기능, Arrow 기능 및 ternary 연산자를 사용하여 한 줄로 목표를 달성합니다.이름이 한 단어일 경우 처음 두 글자만 사용하고, 그 이상일 경우 이름과 성 첫 글자를 사용합니다.(단일 단어 이름 사용 사례를 상기시켜 주셔서 감사합니다.)

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

이름과 성 이니셜을 얻으려면 아래 기능을 사용해 보십시오.

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

일어난 일:함수는 들어오는 문자열을 분할하고, 이름과 성 사이의 이름을 무시하며 이니셜을 반환합니다.단일 이름을 입력한 경우 하나의 이니셜이 반환됩니다.도움이 됐으면 좋겠네요, 건배.

나는 오늘 내 리액트 코드에서 메소드 역할을 하기 위해 이것이 필요했습니다.저는 주에서 사용자 이름을 소품으로 받고 있었습니다.그 후 저는 구성품의 소품 안에 제 방법을 집어넣었습니다.

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

function getInitials(name) {
  return (
    name
      .match(/(?<=\s|^)\p{L}\p{Mn}*/gu)
      ?.filter((el, i, array) => i === 0 || i === array.length - 1)
      .join("") || ""
  );
}

console.log(getInitials('ÇFoo Bar 1Name too ÉLong'));
console.log(getInitials('Q̈lice Hwerty')); // Q is followed by U+0308 (Combining Diaeresis)
console.log(getInitials('A Foo'));
console.log(getInitials('Bob'));

Safari는 정규 표현식(caniuse 참조)을 아직 지원하지 않으므로 Safari 지원이 필요한 경우 다음과 같은 방법으로 다시 작성할 수 있습니다.

function getInitials(name) {
  return (
    name
      .match(/(\s|^)\p{L}\p{Mn}*/gu)
      ?.filter((el, i, array) => i === 0 || i === array.length - 1)
      .map(el => el.trimStart())
      .join("") || ""
  );
}
const name = 'First Second Third'

name
    .split(' ')
    .slice(0, 2) // <= optional if only two letters are desired
    .map((name) => name[0])
    .join('')

// FS

  const getInitials = name => {
    let initials = '';
    name.split(' ').map( subName => initials = initials + subName[0]);
    return initials;
  };
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);

중간 이름과 이름만 포함한 대부분의 경우(@njmwas answer의 확장명)에 적용됩니다.

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

ES6 Destructering을 사용하는 간편한 방법:

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

이름을 전달하여 이니셜 기능을 얻는 것만으로 이름의 이니셜을 얻을 수 있도록 도와주는 간단한 유틸리티 방법입니다. // 예를 들어 이니셜을 얻으세요("해리포터") ==> "HP"

const getInitials = (name) => {
  var parts = name.split(' ')
  var initials = ''
  for (var i = 0; i < parts.length; i++) {
    if (parts[i].length > 0 && parts[i] !== '') {
      initials += parts[i][0]
    }
  }
  return initials.toUpperCase();
}

더 기능적인 것: D

  const getInitials = (string) => {
        const [firstname, lastname] = string.toUpperCase().split(' ');
        const initials = firstname.substring(0, 1);
        return lastname
          ? initials.concat(lastname.substring(0, 1))
          : initials.concat(firstname.substring(1, 2));
      };

console.log(getInitials('FirstName LastName')); // FL
console.log(getInitials('FirstName MiddleName LastName')); // FM
console.log(getInitials('FirstName')); // FI
var getInitials = function (string) {
var names = string.split(' '),
initials = names[0].substring(0, 1).toUpperCase()+'.';

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

console.log(가져오기)이니셜('라마 크리슈나 나라얀');

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

더 좋은 방법.

nameToInitials(name: string): string {
    const portions = name.split(' ')
        .map(val => val[0]);

    return portions.slice(0, 2)
        .reduce((a, b) => a + b, '').toUpperCase();
}

제가 뭔가 오해했다면 죄송합니다만, 대부분의 대답은 너무... 복잡합니다.

제 해결책은 (국제적인 이름, 실제 헝가리 이름의 경우)입니다.

var regex = /[A-ZÍÉÁŰŐÚÖÜÓ]{1}/g
var monogram = 'Üveges Tóth Ödön'.match(regex).join('')

여기엔 복잡한 답들이 많아요...

Clean 코드로 보다 간편한 솔루션!

이 질문이 꽤 오래전부터 있었던 것은 알지만, 이 솔루션은 여러분과 공유하기에 충분하다고 생각합니다 :)

이 코드를 사용하는 저의 목표는 지능적이면서도 읽기 쉬운 것을 만드는 것입니다.

const names = [
  'Crystals', // -> CR
  'undisclosed desires', // -> UD
  'Feel so Close - Radio Edit', // -> FE
  ' ', // -> empty
  'Faint ', // -> FA .: Note the space after the name
]

function getInitials(fullName) {
  const [firstName, ...restNames] = fullName.toUpperCase().trim().split(' ')

  if (!restNames.length) {
    return firstName.substring(0,2)
  }

  const firstNameInitial = firstName[0]
  const lastNameInitial = restNames.pop()[0]

  return `${firstNameInitial}${lastNameInitial}`
}

console.log(names.map(getInitials))

첫 번째 줄은 문자열을 대문자로 변환하고(시작과 끝에) 원하지 않는 공백을 제거한 다음 이름을 분할하여 배열을 만듭니다.파괴를 이용해 우리가 회복하는 것은firstName그리고 나머지를 상수라는 것에 넣습니다.restNames

const [firstName, ...restNames] = fullName.toUpperCase().trim().split(' ')

그런 다음 이름 외에 다른 이름이 있는지 확인하고, 그렇지 않다면 처음 두 글자를 반환하여 기능 실행을 종료합니다.

if (!restNames.length) {
  return firstName[0].substring(0,2)
}

restNames에 다른 이름이 포함되어 있는 것을 발견하면 이름과 성 이니셜을 얻을 수 있습니다.

const firstNameInitial = firstName[0]
const lastNameInitial = restNames.pop()[0]

드디어 이니셜을 돌려드립니다!

return `${firstNameInitial}${lastNameInitial}`

이 코드는 원하는 결과를 명확하고 효율적으로 제공하는 것을 목표로 합니다.

언급URL : https://stackoverflow.com/questions/33076177/getting-name-initials-using-js