맨땅헤딩! 2023. 5. 9. 10:12

해당 포스트는 제로베이스 오프라인스쿨 진행 과정 중 JS PairProgramming과제를 진행하며 회고를 정리하는 글이다.

 

03 Is palindrome TIL
1. 정규표현식
한글을 검색하는 방법: /[ㄱ-힣]/g

2. isPalindrome
palindrome인지 검사하는 함수 isPalindrome을 만들었다.

const isPalindrome = content => {
  const tmpContent = content.toLowerCase().replace(/[^a-z0-9ㄱ-힣]/g, '');

  return tmpContent === [...tmpContent].reverse().join('');
};


위 방법에서는 tmpContent가 빈 문자열이라면 true가 나오게 된다. 빈문자열 ''은 거꾸로 만들어도 ''이기 때문에, 비교를 하면 true가 된다. 그렇다면, content로 '!@!', '!@#'같은 특수문자들로만 이루어진 문자열이 들어올 때 true를 반환하게 된다.

이 문제를 해결하기 위해서 빈문자열을 검사하는 코드를 추가했다.

const isPalindrome = content => {
  const tmpContent = content.toLowerCase().replace(/[^a-z0-9ㄱ-힣]/g, '');

  return tmpContent !== '' && tmpContent === [...tmpContent].reverse().join('');
};


<배운점>
++ 한글을 검사하는 정규표현식이 [ㄱ-ㅎㅏ-ㅣ가-힣] 방법 뿐만아니라 [ㄱ-힣] 방법도 가능하다는 것을 알게되었다.