Replace With Alphabet Position

SungJunEun·2021년 11월 4일
0

Codewars 문제풀이

목록 보기
7/26
post-thumbnail

Description:

Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1"b" = 2, etc.

Example

alphabetPosition("The sunset sets at twelve o' clock.")

Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)


My solution:

function alphabetPosition(text) {
//make string to array
const textArray = text.split('');

// one-to-one corresponce from a~z to 1~26 by ASCII code
const modify = textArray.map(element => {
    return element.toLowerCase().charCodeAt()-96;
  });

// remove items which are not alphabets
const result = modify.filter(element => {
    return (0<element) && (element<27);
  });

//make array into string with black in between
const modifiedstring = result.join(' ');
  return modifiedstring;
}
  • Array.map(callback(element))

    배열의 각 요소마다 callback을 호출해서 결과를 모아 새로운 배열을 반환한다. forEach 함수와의 차이가 바로 단지 실행하느냐 아니면 실행한 값을 새로운 배열로 반환하냐이다.

Best solutions:

function alphabetPosition(text) {
  return text
    .toUpperCase()
    .match(/[a-z]/gi)
    .map( (c) => c.charCodeAt() - 64)
    .join(' ');
}
  • String.match(regexp)

    • regexp

      정규표현식

    문자열 중에 정규식과 일치하는 것들을 모아서 배열로 반환한다.

  • 정규표현식 /[a-z]/gi

    a~z사이와 일치하는 문자를 글로벌하게, 대문자, 소문자 상관없이 찾아라.

Best solution에서는 match를 이용하여서 내가 split과 filter를 이용해 2번의 과정을 거친 것을 한번의 스텝으로 구현하였다.

profile
블록체인 개발자(진)

0개의 댓글

관련 채용 정보