[Javascript] replace(), replaceAll() 과 정규표현식
Javascript에는 replace와 replaceAll이라는 함수가 있다. string에서 문자열을 다른 문자열 바꿔주는 역할을 하는데
둘다 첫번째 인자로 바꾸고 싶은 문자열을 두번째 인자로는 바꿀 문자열을 받는다. 이 때 첫번째 문자열은
정규표현식으로 쓸 수 있는데 이번 포스팅은 그것에 관한 것이다.
일단 둘의 차이점은 함수의 이름에서 유추해 볼 수 있듯이 replace는 문자열에서 첫번째로 발견된 문자열만 교체하고
replaceAll은 발견되는 모든 문자열을 교체한다. 예시를 보자
replace()의 예시
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
replaceAll()의 예시
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replaceAll('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
// Global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
출처는 MDN의 예시를 그대로 가져왔다. 위의 예시에서 알 수 있듯이 두 예제의 첫번째 예시(p.replaceAll('dog', 'monkey'))는 replace는 첫번째로 발견된 'dog'만 바꾸었지만 replace의 all의 경우는 그 문자열의 모든 'dog'를 'monkey'로 교체한것을 볼 수 있다.
우리가 주목해봐야할 예제는 두번째 예제인데 regex로 /Dog/i, 와 /Dog/ig가 각각의 정규표현식으로 등록되어있다.
/Dog/를 찾는데 i를 정규식플래그로 두어 대소문자를 구별하지 않고 찾겠다는 뜻이다. 그래서 Dog로 썼음에도 dog도 monkey로 바뀐것이다. 그런데 g는 global인데 replaceAll의 경우는 정규표현식을 첫번째 매개변수로 넣을 경우 저 g플래그를 반드시 명시해주어야한다. 모든 문자열에서 찾겠다는 의미이다. 그렇다면 replace에도 저 g플래그를 붙여주면 어떻게 될까? replaceAll()과 완벽하게 동일하게 동작한다!