Select content within parenthesis using regex

I am trying to alert the numbers that fall within the parenthesis:

var str2 = "This is a string (3444343) with numbers.";
var patt2 = \((.*?)\);
alert(str2.match(patt2));

jsfiddle: http://jsfiddle.net/BinaryAcid/8nx9v/1/

Upvotes: 2

Views: 5398

Answers (3)

haylem
haylem

Reputation: 22663

Solution

Based on your original question, this would do:

var str2 = "This is a string (3444343) with numbers.";
var patt2 = /\((.*?)\)/;

alert(str2.match(patt2)[1]);

An updated jsFiddle example: http://jsfiddle.net/S99jd/

For your input string, it alerts 3444343 (without parenthesis).

Some Explanations

Your snippet needed:

  • to add forward-slashes / to create the regex,
  • to alert by selecting the correct matching group (here, at index 1, as match() returns an array of elements, where element at index0 is the full match and following indexes correspond to the matching groups).

For a lot more information and help on using regular expressions in JavaScript / ECMAScript, visit: http://www.regular-expressions.info/javascript.html

Upvotes: 9

DVK
DVK

Reputation: 129383

As others noted, it's better if you use slashes to create the regex, but if you wish to know how to fix your approach:

var patt2 = '(\\(\\d+\\))';

or

var patt2 = '([(]\\d+[)])';

Upvotes: -1

Ry-
Ry-

Reputation: 224867

You need to enclose your regular expression literal with forward slashes:

var patt2 = /\((.*?)\)/;

Here's the updated jsFiddle.

Upvotes: 2

Related Questions