JavaScript Uncaught TypeError: regex.test is not a functionの解決方法

環境
Google Chrome  114.0.5735.199(Official Build) (64 ビット)
Windows 11 Pro 64bit

操作例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const regex = '/[0-9]/';
const result = regex.test('456');
console.log(result);
const regex = '/[0-9]/'; const result = regex.test('456'); console.log(result);
const regex = '/[0-9]/';

const result = regex.test('456');

console.log(result);

エラーメッセージ
Uncaught TypeError: regex.test is not a function

原因
正規表現は「引用符」で囲まれていると「文字列」として認識されます。

修正後

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const regex = /[0-9]/;
const result = regex.test('456');
console.log(result);
const regex = /[0-9]/; const result = regex.test('456'); console.log(result);
const regex = /[0-9]/;

const result = regex.test('456');

console.log(result);

実行結果
true

JavaScript

Posted by arkgame