javascript エラー「Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument」の解決方法
- 作成日 2022.08.06
- javascript
- javascript
javascriptで、エラー「Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument」が発生した場合の原因と解決方法を記述してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
エラー内容
以下のコードを実行時に発生
const str = "2022-07-07";
const regexp = /(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/g;
for (const match of str.matchAll(regexp)) {
console.log(match);
}
エラーメッセージ
Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument
画像
firefox(バージョン102)でも、以下のエラーとなります。
Uncaught TypeError: matchAll must be called with a global RegExp
画像
safari15.5の場合は、以下のエラーとなります。
TypeError: String.prototype.matchAll argument must not be a non-global regular expression
画像
原因
「matchAll」を使用する場合は、「グローバルフラグ(g)」が必須なため
解決方法
「グローバルフラグ(g)」を使用する
const str = "2022-07-07";
const regexp = /(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/g;
for (const match of str.matchAll(regexp)) {
console.log(match);
}
実行結果
-
前の記事
PostgreSQL アルファベットの大文字を小文字に変換する 2022.08.05
-
次の記事
SolidJS Tailwind CSSを使用する 2022.08.06
コメントを書く