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

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

javascriptで、エラー「Uncaught TypeError: xxx.replace is not a function」が発生した場合の原因と解決方法を記述してます。文字列以外に「replace」を使用したときに発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャした結果も掲載してます。

環境

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

エラー内容

以下の、数値に対して「replace」実行したコードにて発生。

const num = 123456;

const result = num.replace( /\d/g, '*' ); // ← エラーが発生

console.log( result );

エラーメッセージ

Uncaught TypeError: num.replace is not a function

画像

firefox107の場合でも同じエラーが発生します。

Uncaught TypeError: num.replace is not a function

画像

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

TypeError: num.replace is not a function. (In 'num.replace( /\d/g, '*' )', 'num.replace' is undefined)

画像

原因

「replace」は、数値に使用できないため、以下のように配列内に数値があった場合もエラーとなります。

const arr = ['A11', 111, '222'];

const result = arr.map(function (v) {
  return v.replace( /\d/g, '*' );;
});
// Uncaught TypeError: v.replace is not a function

console.log( result );

解決方法

「toString()」で、文字列に変換してから実行する。

const num = 123456;

const result = num.toString().replace( /\d/g, '*' );

console.log( result ); // ******

または、文字列であるかを判定してから使用します。

const num = 123456;

const result = typeof num === 'string' ? num.replace(/\d/g) : '文字列ではありません';

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