How to use exec() Method In Javascript

For searching a pattern if it is present then returns the entire string otherwise returns an empty string.

const regex = /pattern(g1)(g2)/; 
const match = regex.exec(inputString);

The matched groups can be accessed using numeric indexes. The index 0 represents the entire matched string, and subsequent indexes represent the captured groups.

Example: Extracting parts of a date

Javascript
const regex = /(\d{2})-(\d{2})-(\d{4})/;
const inputString = '27-06-2023';
const match = regex.exec(inputString);

const day = match[1];
const month = match[2];
const year = match[3];

console.log(day);  
console.log(month);
console.log(year);

Output
27
06
2023

How to Access Matched Groups in a JavaScript Regular Expression ?

Accessing matched groups in a JavaScript regular expression allows you to extract specific parts of a string based on patterns defined within parentheses in the regex pattern. This capability enables precise extraction and manipulation of text data, enhancing the versatility of regular expressions in string processing tasks.

In this article, we will learn how to access the matched groups in a JavaScript regular expression. There are two approaches to access the matched groups, these are:

Table of Content

  • Using exec() Method
  • Using match() Method

Similar Reads

Using exec() Method

For searching a pattern if it is present then returns the entire string otherwise returns an empty string....

Using match() Method

For searching a pattern if it is present then it returns true otherwise returns false....

Contact Us