javascript
  1. javascript-match

JavaScript match()

Syntax

The match() method is a built-in string method in JavaScript that searches a string for a specified pattern, and returns an array containing all the matches found in the string. It takes a regular expression or a string argument as input.

The syntax for using match() method is as follows:

string.match(searchValue);

Example

Let's consider an example where we want to extract all the occurrences of the word "fox" in a given string:

let str = "The quick brown fox jumps over the lazy dog";

let matches = str.match(/fox/g);

console.log(matches);

The output of the above code will be an array containing the word "fox":

["fox"]


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Output</title>
</head>
<body>

<!-- Your JavaScript code goes here -->
<script>
  let str = "The quick brown fox jumps over the lazy dog";

  // Using regular expression to find all occurrences of "fox"
  let matches = str.match(/fox/g);

  // Displaying the result in the HTML document
  document.write('<p>' + JSON.stringify(matches) + '</p>');
</script>

</body>
</html>
Try Playground

Explanation

The match() method is a useful string method that allows us to search for a specified pattern in a string and return all the matches found as an array. It takes a regular expression as an argument, which can be used to search for a pattern, and the g (global) flag can be used to search for all the occurrences of the pattern in the string.

If a string argument is passed instead of a regular expression, the method will automatically convert it to a regular expression object with the RegExp() constructor.

Use

The match() method can be used in many different scenarios, such as:

  • Extracting parts of a string that match a specific pattern
  • Validating user input in web forms
  • Parsing text for specific keywords or phrases

Important Points

The following are some important points to consider when using the match() method:

  • The match() method is case sensitive, so it will only match instances of the pattern that have the same casing as the pattern itself.
  • If the regular expression does not contain the g flag, only the first occurrence of the pattern will be returned.
  • If no matches are found, the method will return null.

Summary

The match() method is a built-in string method in JavaScript that allows us to search for a specified pattern in a string and return an array containing all the matches found. It takes a regular expression or a string argument as input, and can be used in a variety of different scenarios to extract, validate, or parse text.

Published on: