JavaScript match() method
The match()
method in JavaScript is used to search a string for a match against a regular expression (regexp). It returns an array containing the results of the match, or null
if no match is found. This method is useful for extracting information from a string based on specific patterns defined by regular expressions.
Syntax:
regexp
: A regular expression object or a string that represents the regular expression to search for in the string.
Return Value:
- Returns an array containing the matched results. If there are no matches, it returns
null
. - If the regular expression has the global flag (
g
), the return value is an array of all matches found in the string. - If the global flag is not used, the return value is an array with the first match and additional properties, such as
index
(the index of the match) andinput
(the original string).
Example 1: Basic Usage
In this example, the match()
method finds the substring "quick"
in the text and returns an array containing the match.
Example 2: No Match Found
If the regular expression does not match anything in the string, match()
will return null
.
Example 3: Using the Global Flag (g
)
If the regular expression includes the global flag (g
), the method returns an array of all matches found in the string.
Example 4: Extracting Substrings with Parentheses
If you use capturing groups in your regular expression, match()
will return additional elements in the resulting array.
Example 5: Using Regular Expressions with Flags
You can create regular expressions with flags using the RegExp
constructor, which can be passed to match()
.
Example 6: String Representation of a Regular Expression
You can also pass a string to match()
, but it will be treated as a pattern without any flags.
Summary:
- The
match()
method is used to search for matches against a regular expression in a string. - It returns an array of matches or
null
if no matches are found. - With the global flag (
g
), it returns all matches; without it, it returns details about the first match. - Capturing groups in the regular expression allow extraction of specific substrings from the matched results.
- You can create regular expressions with flags using the
RegExp
constructor to customize the search behavior.