Luke Dennis
Luke Dennis

Reputation: 14550

Retrieve only a portion of a matched string using regex in Javascript

I've got a string like

foo (123) bar

I want to retrieve all numbers surrounded with the delimiters ( and ).

If I use varname.match(/\([0-9]+\)/), my delimiters are included in the response, and I get "(123)" when what I really want is "123".

How can I retrieve only a portion of the matched string without following it up with varname.replace()?

Upvotes: 4

Views: 265

Answers (1)

John Millikin
John Millikin

Reputation: 200846

Yes, use capturing (non-escaped) parens:

varname.match(/\(([0-9]+)\)/)[1]

Upvotes: 8

Related Questions