JavaScript(JS) string method - match

www‮.‬theitroad.com

The match() method is a string method in JavaScript that is used to search for a pattern in a string and return an array of matches, or null if no matches are found. The pattern can be either a regular expression or a string.

Here is the syntax for the match() method:

str.match(regexp)

Here, str is the original string you want to search in, and regexp is the regular expression or string pattern you want to search for.

The match() method returns an array of matches found in the string. If no matches are found, it returns null. The array contains the matched substrings and any captured groups specified in the regular expression pattern.

Here is an example of using the match() method with a regular expression pattern:

let str = "The quick brown fox jumps over the lazy dog.";
let pattern = /[A-Z]/g;
let result = str.match(pattern);
console.log(result); // ["T", "B", "F"]

In the example above, the match() method searches the str for any uppercase letters and returns an array of the matches found. The regular expression pattern /[A-Z]/g matches any uppercase letter and the g flag specifies a global search that finds all matches. The resulting array contains the substrings "T", "B", and "F", which are the uppercase letters found in the string.

Here is an example of using the match() method with a string pattern:

let str = "The quick brown fox jumps over the lazy dog.";
let pattern = "quick";
let result = str.match(pattern);
console.log(result); // ["quick"]

In the example above, the match() method searches the str for the string "quick" and returns an array with the single match found. Since there is only one match, the resulting array contains the substring "quick".