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

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

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

環境

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

エラー内容

以下の、文字列に対して「substring」を実行したコードにて発生。

const num = 12345;

const result = num.substring(0, 2);

エラーメッセージ

Uncaught TypeError: num.substring is not a function

画像

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

Uncaught TypeError: num.substring is not a function

画像

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

TypeError: num.substring is not a function. (In 'num.substring(0, 2)', 'num.substring' is undefined)

画像

原因

「substring」は、数値には使用できないため。以下のように文字列には使用できます。

const num = '12345';

const result = num.substring(0, 2);

console.log( result ); // 12

解決方法

一度「toString()」で文字列に変換して使用する。

const num = 12345;

const result = num.toString().substring(0, 2);

console.log( result ); // 12

console.log( typeof result ); // string

console.log( Number(result) ); // 12

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

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

const num = 12345;

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

console.log( result ); // 12