How to Extract a Substring from a String in JavaScript Using Parentheses?

Estimated read time 1 min read

To extract a substring from a string in JavaScript using parentheses, you can use a regular expression with capturing groups. Here’s an example:

const string = "I have a cat and a dog";
const regex = /I have a (cat|dog)/;
const match = string.match(regex);
console.log(match[1]); // Output: "cat"

Here’s what the regular expression does:

  • I have a – matches the string “I have a “
  • (cat|dog) – matches either “cat” or “dog” and captures it as a group

The parentheses around “cat|dog” create a capturing group that allows you to extract the matched substring. The first capturing group is referred to as $1, the second one as $2, and so on. In this case, the captured substring is “cat”, so we access it using match[1].

The string.match(regex) method returns an array of all matches. In this case, it will return an array with two elements: the entire matched string (“I have a cat”) and the captured substring (“cat”). We use array indexing (match[1]) to access the captured substring.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply