Home > Web Front-end > JS Tutorial > How to Extract Strings Enclosed in Parentheses using JavaScript Regular Expressions?

How to Extract Strings Enclosed in Parentheses using JavaScript Regular Expressions?

Patricia Arquette
Release: 2024-11-11 22:37:03
Original
873 people have browsed it

How to Extract Strings Enclosed in Parentheses using JavaScript Regular Expressions?

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]);
Copy after login

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
Copy after login

  1. )

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template