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.
The syntax of String.match() method is:
match(regexp)
This match() method of String used to match regular expression regexp against a string.
Parameter | Optional/Required | Description |
---|---|---|
regexp | required | A regular expression object. If a non-RegExp object is passed, it is implicitly converted to a RegExp. |
String.match() returns value of type Array
, or null
.
In this example, we use the match()
method to find all occurrences of the letter 'o' in a string.
For example,
str
with the value 'Hello World'
.match()
method on str
with the regular expression /o/g
to find all matches of the letter 'o'.matches
.matches
to the console using console.log()
method.const str = 'Hello World';
const matches = str.match(/o/g);
console.log(matches);
['o', 'o']
This example demonstrates using the match()
method to find all words in a string.
For example,
text
with the value 'The quick brown fox'
.match()
method on text
with the regular expression /\b\w+\b/g
to find all words.words
.words
to the console using console.log()
method.const text = 'The quick brown fox';
const words = text.match(/\b\w+\b/g);
console.log(words);
['The', 'quick', 'brown', 'fox']
In this example, we use the match()
method to search for a pattern that does not exist in the string.
For example,
str
with the value 'Hello World'
.match()
method on str
with the regular expression /z/
to search for the letter 'z'.null
because the pattern does not exist, is stored in the variable noMatch
.noMatch
to the console using console.log()
method.const str = 'Hello World';
const noMatch = str.match(/z/);
console.log(noMatch);
null
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.