Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

javascript - 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 match to be closest solution.

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

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

my results with

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

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

is also ["{"a":"one"}"]

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

what wrong is happening here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...