JavaScript String match() Method - JavaScript Tutorial

JavaScript String match() Method

BLUF: This tutorial on JavaScript String match() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript String match() Method

Understanding JavaScript String match() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Example

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.

Example

<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.

Example

<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.

Example

<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:

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.

Example

<script>

var str="Example";

document.writeln(str.match(/[a-p]/g));

</script>

Output:

Output

a,a,p,o,i,n

Example 6

Now, let's explore the identical illustration without employing global search functionality.

Example

<script>

var str="Example";

document.writeln(str.match(/[a-p]/));//return the first match

</script>

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience