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
| Parameter | Optional/Required | Description |
|---|---|---|
regexp | required | A 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,
- We define a string variable
strwith the value'Hello World'. - We call the
match()method onstrwith the regular expression/o/gto find all matches of the letter 'o'. - The result, which is an array containing all matches, is stored in the variable
matches. - We log
matchesto the console usingconsole.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,
- We define a string variable
textwith the value'The quick brown fox'. - We call the
match()method ontextwith the regular expression/\b\w+\b/gto find all words. - The result, which is an array containing all words, is stored in the variable
words. - We log
wordsto the console usingconsole.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,
- We define a string variable
strwith the value'Hello World'. - We call the
match()method onstrwith the regular expression/z/to search for the letter 'z'. - The result, which is
nullbecause the pattern does not exist, is stored in the variablenoMatch. - We log
noMatchto the console usingconsole.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.