codeofnode codeofnode - 1 year ago 86
Javascript Question

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

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

After searching i found

to be closest solution.

But trying this with grouping of
, it does not give suitable result.

My object is

and regex i am building is
new RegExp('{"a":"(.*)"}','g')

my results with

'{"a":"one"}'.match(new RegExp('{"a":"(.*)"}','g'))

'{"a":"one"}'.match(new RegExp('{"a":"(.*)"}'.replace(/([+?^=!:${}|\[\]\/\\])/g, "\\$1"),'g'))

is also

I am expecting the result should have been
["{"a":"one"}", "one"]

what wrong is happening here?

Answer Source

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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download