8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptで括弧の中身の文字列を取得するメモ【2020】

Posted at

Javascriptで括弧の中身の文字列を取得するメモのアップデート版。

()の中身を取り出したい時。

let str = "aaa(bbb)ccc";
console.log(str.match(/\((.+)\)/)[1]);

// output: bbb

{}の中身を取り出したい時。
([1]をなくせば様々な情報がセットで手に入ります。)

let str = "aaa{bbb}ccc";
console.log(str.match(/\{(.+)\}/)[1]);

// output: bbb

{}で囲まれた複数の要素を取り出したい時。
(/gがあれば複数取得できます。)

let str = "aaa{bbb}ccc{ddd}";
console.log(str.match(/\{.*?\}/g));

// output: (2) ["{bbb}", "{ddd}"]

情報源:[https://teratail.com/questions/156083]

{}で囲まれた複数の要素を取り出すんでなく、大きく取り出したい時。
(?があればできるだけ短いものを探索してくれるので上のような状態になります。)

let str = "aaa{bbb}ccc{ddd}";
console.log(str.match(/\{.*\}/g));

// output: (2) ["{bbb}ccc{ddd}"]

もっと詳しく

Javascript 正規表現入門

8
7
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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?