Javascript String match()

The match() method returns the result of matching a string against a regular expression.

Example

const message = "JavaScript is a fun programming language.";

// regular expression that checks if message contains 'programming'
const exp = /programming/;

// check if exp is present in message let result = message.match(exp);
console.log(result); /* Output: [ 'programming', index: 20, input: 'JavaScript is a fun programming language.', groups: undefined ] */

match() Syntax

The syntax of the match() method is:

str.match(regexp)

Here, str is a string.


match() Parameters

The match() method takes in:

  • regexp - A regular expression object (Argument is implicitly converted to RegExp if it is a non-RegExp object)

Note: If you don't give any parameters, match() returns [""].


match() Return Value

  • Returns an Array containing the matches, one item for each match.
  • Returns null if no match is found.

Example 1: Using match()

const string = "I am learning JavaScript not Java.";
const re = /Java/;

let result = string.match(re);
console.log("Result of matching /Java/ :"); console.log(result); const re1 = /Java/g;
let result1 = string.match(re1);
console.log("Result of matching /Java/ with g flag:") console.log(result1);

Output

Result of matching /Java/ :
[
  'Java',
  index: 14,
  input: 'I am learning JavaScript not Java.',
  groups: undefined
]
Result of matching /Java/ with g flag:
[ 'Java', 'Java' ]

Here, we can see that without using the g flag, we get only the first match as a result but with detailed information like index, input, and groups.

Note: If the regular expression does not include the g flag, str.match() will return only the first match similar to RegExp.exec(). The returned item will also have the following additional properties:

  • groups - An object of named capturing groups having keys as the names and values as the captured matches.
  • index - The index of search where the result was found.
  • input - A copy of the search string.

Example 2: Matching sections in string

const string = "My name is Albert. YOUR NAME is Soyuj.";

// expression matches case-insensitive "name is"+ any alphabets till period (.)
const re = /name\sis\s[a-zA-Z]+\./gi;

let result = string.match(re);
console.log(result); // [ 'name is Albert.', 'NAME is Soyuj.' ] // using named capturing groups const re1 = /name\sis\s(?<name>[a-zA-Z]+)\./i;
let found = string.match(re1);
console.log(found.groups); // {name: "Albert"}

Output

[ 'name is Albert.', 'NAME is Soyuj.' ]
{name: "Albert"}

Here, we have used a regular expression to match a certain portion of the string. We can also capture certain groups in the match using the syntax as shown above.


Recommended Reading: JavaScript String matchAll()

Did you find this article helpful?