Finding Strings between Parentheses using Regular Expressions in JavaScript
To retrieve strings enclosed within parentheses, consider using regular expressions. Regular expressions can match specific patterns within text, including parentheses.
To achieve this, create an escaped set of parentheses ( and ) to match the actual parentheses, and within that, use a capturing group () to capture the desired string.
For example, consider the following code:
var regExp = /\(([^)]+)\)/; var matches = regExp.exec("I expect five hundred dollars (0)."); // matches[1] contains the value between the parentheses console.log(matches[1]);
In this example, the regular expression regExp matches parentheses with the pattern ( followed by one or more characters not enclosed in parentheses 1 , and captures this interior string within ()`.
When applied to the input string "I expect five hundred dollars ($500)." using exec(), it returns an array matches. The first element matches[0] contains the entire matched string, including the parentheses. To retrieve only the string between parentheses, access matches[1], which yields:
0
The above is the detailed content of How to Extract Strings Enclosed in Parentheses using JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!