Why doesn't String#match() result contain captured values?

后端 未结 1 884
一生所求
一生所求 2020-12-07 04:32

I am trying to extract a value from simplest JSON in javascript.

After searching i found match to be closest solution.

But trying this with grou

相关标签:
1条回答
  • 2020-12-07 04:51

    See String#match() reference:

    If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned.

    Remove g modifier to get the expected results.

    console.log(
       '{"a":"one"}'.match(/{"a":"(.*)"}/)
    );
    
    Or, if you need to get multiple matches, use `RegExp#exec` in a loop or - with the latest JS environments - `String#matchAll`:
    
    <!-- begin snippet: js hide: false console: true babel: false -->

    And the matchAll variant:

    const s = '{"a":"one","a":"two"}', regex = /"a":"([^"]*)"/g;
    const results = Array.from([...s.matchAll(regex)], m => m[1]);
    console.log(results);

    0 讨论(0)
提交回复
热议问题