AppDividend
Latest Code Tutorials

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

0

Javascript String Match Example | String.prototype.match() is today’s topic. The javascript string match() method retrieves the matches when matching a string against a regular expression. The 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 javascript string match() method will return only the first match in the string.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript String Match Example

The syntax for String match() method is following.

string.match(regexp)

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/);
console.log(newArray);

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/);
console.log(newArray);

 

String.prototype.match()

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.

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

Leave A Reply

Your email address will not be published.

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