The match method in JavaScript is utilized for matching a string with a regular expression. When employing the match method, appending the global search modifier enables retrieving all matching elements; otherwise, solely the initial match is returned.
Syntax
The syntax for the match method is as follows:
string.match(regexp)
Parameter
RegExp is an abbreviation for regular expression, which signifies the pattern to be located within a text.
Return
The matched regular expression.
JavaScript String match Method Example
Let's see some simple examples of match method.
Example 1
Let's see a simple example to search for a match.
<script>
var str="Example";
document.writeln(str.match("Java"));
</script>
Output:
Example 2
In this instance, we will demonstrate how to locate a regular expression utilizing the global flag.
<script>
var str="Example";
document.writeln(str.match(/Java/g));
</script>
Output:
Example 3
Let's explore another instance of searching for a regular expression with the global flag. Since the match method is sensitive to cases, it will return null in such scenarios.
<script>
var str="Example";
document.writeln(str.match(/java/g));
</script>
Output:
Example 4
To disregard case sensitivity in the behavior of the match method, we can utilize the ignore flag. Let's illustrate this with an example:
<script>
var str="Example";
document.writeln(str.match(/java/gi));
</script>
Output:
Example 5
In this section, we will display the array containing elements that have been matched.
<script>
var str="Example";
document.writeln(str.match(/[a-p]/g));
</script>
Output:
a,a,p,o,i,n
Example 6
Now, let's explore the identical illustration without employing global search functionality.
<script>
var str="Example";
document.writeln(str.match(/[a-p]/));//return the first match
</script>
Output: