크고 작은 문제들/바보짓 모음

[JavaScript] String.prototype.replace - undefined가 삽입되는 문제

노새두마리 2023. 9. 22. 14:15

문제

  • 문자열로부터 정규표현식에 해당하는 부분을 제거하려 하였으나, undefined가 삽입되는 현상이 발생하였습니다.
  • replace 함수의 두 번째 인자가 생략되었기 때문입니다.
// 반복문 내부 코드

// 탐색 대상 letter 정규표현식 생성
const regexp = new RegExp(letter, 'g');
    
// 발견된 문자열의 개수를 결과에 더하기(옵셔널 체이닝 ?, null 병합 연산자 ?? 사용)
result += input.match(regexp)?.length ?? 0;

// input으로부터 검사 완료된 문자열을 전부 제거
input = input.replace(regexp);

// ddz=z=
// dundefinedz=
// dundefinedundefined

해결

  • replace 함수의 두 번째 인자로써 정규표현식에 일치하는 부분을 대체할 문자열을 전달합니다.
// before
input = input.replace(regexp);

// after
input = input.replace(regexp, '');

깨달은 점

이렇게 사소한 부분에 오류 및 경고를 발생시켜 의도치 않은 동작을 막아주는 것이 얼마나 감사한 일인지 깨달았습니다.

TypeScript Playground


replace(pattern, replacement);
 

String.prototype.replace() - JavaScript | MDN

The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern i

developer.mozilla.org