0
1

More than 1 year has passed since last update.

【JavaScript】正規表現で数値を取得し、変数代入する

Posted at

はじめに

http://localhost:3000/user/1'などのパスの最後の数値を取得し変数代入することがあったので方法を記録しておく。

結論

// 対象となる文字列
const text = 'http://localhost:3000/user/123';

// 正規表現を定義
const regex = /(?<=user\/)([0-9]+)/;

// "()" で指定した箇所が $1 に入る
const found = text.match(regex);

// found[0]で取得可能
console.log("found", found[0])
=> 123

詳細

(?<=user\/)の部分は後読みアサーションといい、上記の例では、取得したい数字の前に、user/が存在する場合のみ、その数字がマッチするようになる。

あとは、text.match(regex)でmatchさせたときに、変数foundには配列でデータが入るので、その一つ目を取得すればいい。

おわりに

先読み・後読みアサーションについて理解することができた。今後も必要に応じて正規表現の使い方を調査していきたい。

0
1
2

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
0
1