Abbreviate a Two Word Name

chris0205.eth·2022년 2월 12일
0

Codewars

목록 보기
2/5
post-thumbnail

Prob

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Sam Harris => S.H

patrick feeney => P.F


Answ

my

function abbrevName(name){
  let blnk = name.indexOf(' ');
  let abN = name.toUpperCase().substr(0,1)+'.'+name.toUpperCase().substr(blnk+1,1);
  
  return abN;
}

문자열에서 특정 문자의 위치를 찾는 indexOf()로 blank의 위치를 찾았다. 그 위치값을 기반으로 단어를 축약했다.

others-1

function abbrevName(name){

  var nameArray = name.split(" ");
  return (nameArray[0][0] + "." + nameArray[1][0]).toUpperCase();
}

split이라는 문자열을 특정 구분자(separtor)로 분리하여 배열로 만들어주는 메서드를 이용해 문제를 해결했다.
이때 독특한 점은 문자열 자체도 배열을 index로 호출하듯이 문자열도 index가 있다는 점이라는 것이다.

var a = 'name';
console.log(a[1]); //expected value : a

위와 같이 사용될 수 있다.

others-2

function abbrevName(name){
    return name.split(' ').map(i => i[0].toUpperCase()).join('.')
}

map 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.

join()은 배열의 모든 요소를 연결해 하나의 문자열로 만든다.


마무리

문자열, 배열과 관련된 메서드들을 더 공부해 볼 수 있었다.

profile
long life, long goal

0개의 댓글