Kimyeongkyung
replace() vs replaceAll() 본문
replace()와 replaceAll()은 공통적으로 치환할 때 사용하는 메서드지만 분명한 차이가 존재한다.
replaceAll()
- 조건 대상이 되는 문자를 모두 치환한다.
- ECMA-262 12th(2021) 스펙을 기준으로 replaceAll() 기능이 추가되었기 때문에 최신을 바탕으로 하는 개발 환경이 아니라면 replaceAll()은 사용하기가 어려움
- 예시
const message = "Hello Hello world!";
document.write(message.replaceAll("Hello", "Happy"));
// 결과
// "Happy Happy world!"
replace()
- 기본적으로 동작하는 방식은 조건 대상이 되는 첫 번째 문자 하나만 치환한다.
- 전달받은 문자를 수정하는 것이 아니라 새로운 값을 만들어 반환한다.
- 예시
const message = "Hello Hello world!";
document.write(message.replace("Hello", "Happy"));
// 결과
// "Happy Hello world!"
만약 replace 메서드를 사용해 모든 문자를 치환하고 싶다면?
replace() + 정규식(RegExp)을 사용할 수 있음 => replaceAll()과 같은 기능
const replaceText = (source, findText, replaceText) => {
return source.replace(new RegExp(`\\${findText}`, 'g'), replaceText);
};
참고자료
'important' 카테고리의 다른 글
Heroku(헤로쿠) 보안코드 인증 실패 문제 해결(feat. Salesforce Authenticator App) (1) | 2024.01.23 |
---|---|
지정 접미사로 끝나는지 판단하는 메서드 endsWith() (0) | 2023.11.11 |
Axios interceptors (0) | 2023.04.12 |
단언 연산자 (!.) (0) | 2023.04.10 |
fatal: too many arguments for a rename operation 에러 (0) | 2023.04.05 |