javascript エラー「Uncaught TypeError: xxx.replaceAll is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.replaceAll is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.replaceAll is not a function」が発生した場合の原因と解決方法を記述してます。正規表現を「’」などの引用符で囲った場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

エラー内容

以下の、数値の「0」を全て「9」に変更しようとしたコードで発生。

const num = 10000;

const result = num.replaceAll('0', '9');

エラーメッセージ

Uncaught TypeError: num.replaceAll is not a function

画像

firefox106の場合では、以下のエラーが発生します。

Uncaught TypeError: num.replaceAll is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: num.replaceAll is not a function. (In 'num.replaceAll('0', '9')', 'num.replaceAll' is undefined)

画像

原因

数値に対して「replaceAll」を使用しているため。「replaceAll」は文字列に使用します。

const result = 'a-b-c'.replaceAll('-','!');

console.log(result); // a!b!c

解決方法

「文字列」に変換して使用するか、

const num = 10000;

const result = num.toString().replaceAll('0', '9');

console.log( result ); // 19999
console.log( typeof result ); // string
console.log( typeof Number(result) ); // number

文字列であるかを判定してから使用する

const num = 10000;

const result = typeof str === 'string' ? num.replaceAll('0', '9') : '文字列ではありません';

console.log( result ); // 文字列ではありません