[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-regex/javascript-string-match/ [Back]  [Original]

JavaScript Regex match(): Match a String Against a Regular Expression
Skip to content

JavaScript Regex match()

Summary: in this tutorial, you’ll learn about the JavaScript String match() method to match a string against a regular expression.

To understand how the match() method works and how to use it effectively, you should have the basic knowledge of regular expression.

Introduction to the JavaScript match() method

The String match() method matches a string against a regular expression:

str.match(regexp);
Code language: JavaScript (javascript)

If the regexp is not a regular expression, the match() will convert it to a regular expression using the RegExp() constructor. The match() returns an array depending on whether the regular expression uses the global flag (g) flag or not:

The match() returns null if it does not find any matches.

JavaScript Regex match() method

Let’s take some examples of using the match() method.

1) Using the JavaScript regex match() method with the expression that has the global flag

The following example shows how to use the match() method with the global flag (g). It returns an array of matches:

let str = "Price: $5$10";
let result = str.match(/\$\d+/g);
console.log(result);
Code language: JavaScript (javascript)

Output:

["$5", "$10"]
Code language: JavaScript (javascript)

In this example, the match() searches for any number that follows the $ sign.

2) Using the JavaScript regex match() method with the expression that has the global flag

The following example illustrates how to use the match() method with a regular expression that doesn’t have a global flag. It returns an array of the first match with additional properties.

let str = "Price: $5$10";
let result = str.match(/\$\d+/);
console.log(result);
Code language: JavaScript (javascript)

Output:

[]

The additional properties are:

3) Using the JavaScript Regex match() method with the named capturing group

The following shows how to use the match() method with a named capturing group. It captures the "yellow" into a group named "color":

let str = 'I like yellow color palette!';

let re = /(?<color>yellow) color/;
let result = str.match(re);

console.log(result);
Code language: JavaScript (javascript)

Output: 

JavaScript String match with named capturing group [JavaScript String match with named capturing group]

In this tutorial, you have learned how to use the JavaScript String match() method to match a string against a regular expression.

Was this tutorial helpful ?
Yes No
Search &hellip;:

Regex Basics

Regex Quantifiers

Sets and Ranges

Regex Grouping

Regex Look Around

Regex Methods

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page