Error

[Error][js]Uncaught TypeError: Cannot read properties of null (reading 'replace')

오선지♬ 2025. 9. 10. 11:05
728x90
반응형

변환할 데이터가 null(또는 undefined) 상태라서 replace 함수를 쓸 수 없는 거예요.

 

 

해결 방법

  • null/undefined 체크 후 실행
const hpNo = this.detail.hpNo || "";
const formattedHpNo = hpNo.replace(/^(\d{3})(\d{3,4})(\d{4})$/, '$1-$2-$3');
 
  • Optional chaining 사용 (ES2020+)
const formattedHpNo = this.detail.hpNo?.replace(/^(\d{3})(\d{3,4})(\d{4})$/, '$1-$2-$3') || "";
 
  • 조건문으로 직접 처리
let formattedHpNo = "";
if (this.detail.hpNo) {
  formattedHpNo = this.detail.hpNo.replace(/^(\d{3})(\d{3,4})(\d{4})$/, '$1-$2-$3');
}
728x90
반응형