JavaScript Tutorials

JavaScript String match()
Syntax & Examples

String.match() method

The match() method of the String class in JavaScript is used to match a regular expression (regexp) against the calling string. It returns an array containing the matches, or null if no match is found.


Syntax of String.match()

The syntax of String.match() method is:

match(regexp)

This match() method of String used to match regular expression regexp against a string.

Parameters

ParameterOptional/RequiredDescription
regexprequiredA regular expression object. If a non-RegExp object is passed, it is implicitly converted to a RegExp.

Return Type

String.match() returns value of type Array, or null.



✐ Examples

1 Using match() method to find matches in a string

In this example, we use the match() method to find all occurrences of the letter 'o' in a string.

For example,

  1. We define a string variable str with the value 'Hello World'.
  2. We call the match() method on str with the regular expression /o/g to find all matches of the letter 'o'.
  3. The result, which is an array containing all matches, is stored in the variable matches.
  4. We log matches to the console using console.log() method.

JavaScript Program

const str = 'Hello World';
const matches = str.match(/o/g);
console.log(matches);

Output

['o', 'o']

2 Using match() method with a pattern to find words

This example demonstrates using the match() method to find all words in a string.

For example,

  1. We define a string variable text with the value 'The quick brown fox'.
  2. We call the match() method on text with the regular expression /\b\w+\b/g to find all words.
  3. The result, which is an array containing all words, is stored in the variable words.
  4. We log words to the console using console.log() method.

JavaScript Program

const text = 'The quick brown fox';
const words = text.match(/\b\w+\b/g);
console.log(words);

Output

['The', 'quick', 'brown', 'fox']

3 Using match() method to find a pattern that does not exist

In this example, we use the match() method to search for a pattern that does not exist in the string.

For example,

  1. We define a string variable str with the value 'Hello World'.
  2. We call the match() method on str with the regular expression /z/ to search for the letter 'z'.
  3. The result, which is null because the pattern does not exist, is stored in the variable noMatch.
  4. We log noMatch to the console using console.log() method.

JavaScript Program

const str = 'Hello World';
const noMatch = str.match(/z/);
console.log(noMatch);

Output

null

Summary

In this JavaScript tutorial, we learned about match() method of String: the syntax and few working examples with output and detailed explanation for each example.