2
0

More than 1 year has passed since last update.

正規表現にマッチする文字列を渡してもRegExp.testがtrueにならない

Last updated at Posted at 2021-12-16

基本的なことですが、少しはまったので備忘のため記します。

やりたかったこと

文字列がURLかどうかを正規表現で判定したい

試したこと 起きたこと

const str = 'https://google.com';
const reg = new RegExp('https?://[\w/:%#\$&\?\(\)~\.=\+\-]+');
reg.test(str); //結果:false

正規表現は合っているはずなのに、マッチする文字列を渡してもfalseが返ってくる…。:thinking::thinking::thinking:

解決方法

コンストラクター構文では正規表現を文字列として指定しているため「\」のエスケープが必要でした。

const reg = new RegExp('https?://[\\w/:%#\\$&\\?\\(\\)~\\.=\\+\\-]+');

正規表現リテラルを使用する場合

const reg = /https?:\/\/[\w\/:%#\$&\?\(\)~\.=\+\-]+/;

参考文献

この記事は以下の情報を参考にして執筆しました。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0