Skip to content
← Back to rules

unicorn/prefer-string-replace-all Pedantic

🛠️ An auto-fix is available for this rule.

무엇을 하는가

정규식의 전역 플래그를 사용할 때, String#replace() 대신 String#replaceAll()를 선호합니다.

왜 문제가 되는가?

String#replaceAll() 메서드는 정규식을 사용할 필요 없으며, 문자열이 리터럴이 아닐 경우 이스케이프 처리를 기억해야 하는 불편함이 없어 더 빠르고 안전합니다. 또한 정규식과 함께 사용될 때 의도가 더욱 명확해집니다.

예시

이 규칙에 부적절한 코드 예시:

js
foo.replace(/a/g, bar);

이 규칙에 적절한 코드 예시:

js
foo.replace(/a/, bar);
foo.replaceAll(/a/, bar);

const pattern = "not-a-regexp";
foo.replace(pattern, bar);

사용 방법

구성 파일 또는 CLI를 통해 이 규칙을 활성화하려면 다음을 사용할 수 있습니다:

json
{
  "rules": {
    "unicorn/prefer-string-replace-all": "error"
  }
}
bash
oxlint --deny unicorn/prefer-string-replace-all

참고자료