javascript エラー「Uncaught TypeError: xxx.replace is not a function」の解決方法
- 作成日 2023.01.03
- javascript
- javascript
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 ); // 文字列ではありません
-
前の記事
Rust ベクタ(可変配列)の値を任意の数で後ろから順番に区切る 2023.01.02
-
次の記事
メモ帳 タブを挿入するショートカットキー 2023.01.03
コメントを書く