정규 표현식(RegEx)과 replace() 메서드를 활용하면 JavaScript로 문자열 내부의 특정 문자를 손쉽게 찾아 모두 교체할 수 있습니다. 이 글에서는 그 기본 원리와 실전 예제를 소개합니다.
문자 교체가 필요한 상황
예를 들어 텍스트를 작성하다가 임대시(em dash, —)를 넣어야 했는데, 실수로 하이픈(hyphen, -)을 입력했다고 가정해 봅시다.
const textBlock =
"When you're typing fast it's normal to make a few spelling mistakes here and there - it just means you're human."
replace() 메서드와 정규 표현식으로 수정하기
다행히 이런 문제는 정규 표현식과 replace() 메서드를 조합하면 간단히 해결할 수 있습니다.
const textBlockCorrected = textBlock.replace(/-/g, "—")
console.log(textBlockCorrected)
// "When you're typing fast it's normal to make a few spelling mistakes here and there — it just means you're human."
여기서 핵심은 정규 표현식 끝에 붙은 g 플래그입니다. g는 'global'의 약자로, 문자열 전체에서 일치하는 모든 문자를 교체하라는 의미입니다. 만약 이 플래그를 생략하면 첫 번째로 발견된 문자 하나만 교체되므로 주의해야 합니다.
결과 비교하기
두 결과가 똑같아 보이나요? 사실은 분명히 다릅니다. 자세히 들여다보세요. 혹은 textBlock과 textBlockCorrected의 출력 결과를 나란히 출력해 보면 차이를 더 쉽게 확인할 수 있습니다.
console.log(textBlock)
// "When you're typing fast it's normal to make a few spelling mistakes here and there - it just means you're human."
console.log(textBlockCorrected)
// "When you're typing fast it's normal to make a few spelling mistakes here and there — it just means you're human."
참고: 타이포그래피에서는 코드 예제에 사용한 것 같은 고정폭(monospace) 폰트가 아니라 일반 가변폭 폰트를 사용할 때 글자와 기호의 차이를 훨씬 쉽게 구분할 수 있습니다. 임대시(em dash), 엔대시(en dash), 하이픈(hyphen)의 세부적인 차이에 대해서는 별도의 타이포그래피 튜토리얼에서 자세히 다룰 예정입니다.