How to use match() Method In Javascript

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

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

Example: Parsing a URL:

Javascript
const regex = /(https?):\/\/([^:/\s]+)(:\d{2,5})?(\/[^\s]*)?/;
const inputString = 
    'https://www.w3wiki.com:8080/path/to/resource';
const match = regex.exec(inputString);

const protocol = match[1];
const domain = match[2];
const port = match[3];
const path = match[4];

console.log(protocol);  
console.log(domain);    
console.log(port);      
console.log(path); 

Output
https
www.w3wiki.com
:8080
/path/to/resource

Conclusion: To access the matched groups in a JavaScript regular expression, we can use the exec() method or the match() method. Capturing groups defined using parentheses () allows for the extraction of extract specific parts of the matched string. Once there is a match object, we can access the matched groups using array indexes.


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