The match() method returns the result of matching a string against a regular expression.
Example
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
RegExpif it is a non-RegExpobject)
Note: If you don't give any parameters, match() returns [""].
match() Return Value
- Returns an
Arraycontaining the matches, one item for each match. - Returns
nullif no match is found.
Example 1: Using match()
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
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()