Latest Code Tutorials

Javascript String Match Example | Javascript match()


Javascript string match method retrieves the matches when matching a string against a regular expression. Javascript match() method searches the string for the match against the regular expression, and returns the matches, as an Array object.

If a regular expression does not include the g modifier to perform a global search, then the javascript string match() method will return only the first match in the string.

Javascript String Match Example

Content Overview

The syntax for the String match() method is the following.


The regexp parameter is required. It is the value to search for, as a regular expression. Let us take an example by creating a file called app.js and add the following code.

We will use the Node.js to run the file and log the output.

// app.js

let str = 'Obama was US president';
let newArray  = str.match(/ba/);

So, in the above example, we have passed the regular expression which is saying that return an array of all the elements satisfying that regular expression.

Save the file and run the file by typing the following command.

node app

Javascript String Match Example | String.prototype.match()

The above regular expression includes the i flag so that upper or lower case differences will be ignored.

The result will an Array, containing the matches, one item for each match, or null if no match is found.

If we do not add /gi, then it will give the output like this.

// app.js

let str = 'Obama was US president';
let newArray  = str.match(/ba/);


If a regular expression does not include a g  flag, then it returns the same result as RegExp.exec() function does.

The returned Array has an extra input property, which contains an original string that was parsed.

Also, it has an index property, which represents the zero-based index of a match in a string.

If a regular expression includes a g flag, the match method returns an Array containing all the matched substrings rather than matched objects.

Captured groups are not returned. If there are no matches, then the function returns null.

Additional properties

As explained above, some results contain additional properties as described below.

  1. groups: An array of named capturing groups or undefined if no named capturing groups were defined. See Groups and Ranges for more information.
  2. index: The index of the search at which the result was found.
  3. input: A copy of the search string.

At last, Javascript String Match Example | String.prototype.match() is over.

Recommended Posts

Javascript String replace()

Javascript String split()

Javascript String indexOf()

Javascript String concat()

Javascript String substring()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.