The match() method in JavaScript is used to retrieve the matches when matching a string against a regular expression. It returns an array containing the matched substrings or null if no matches are found.
Syntax: string.match(regexp)
- regexp: A regular expression object or a string representing a regular expression pattern.
Example:
let str = "The rain in Spain falls mainly in the plain"; let matches = str.match(/ain/g); console.log(matches); // Output: ["ain", "ain", "ain"]
Explanation:
- We have a string str containing "The rain in Spain falls mainly in the plain".
- We use match(/ain/g) to find all occurrences of "ain" in the string.
- The method returns an array ["ain", "ain", "ain"], containing all matches found.
Code Compiler Link: https://app.singhteekam.in/codecompiler/