Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 629
Justice Gödel Conder Avatar asked Sep 18 '26 07:09

Justice Gödel Conder


1 Answers

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

like image 98
haylem Avatar answered Sep 19 '26 21:09

haylem