In this blog post you’ll learn about the JavaScript match() method. The method to match the specified value. And return that value in a form of array.
Description:
match() method matches the given value (regular expression) in a string.
match() method returns null if no match is found.
match() method return array of matches.
Syntax:
JavaScript
string.match(SearchValue);
Parameter Description.
SearchValue: Regular expression with value to search or match in a given string.
Example 1: Find specific letter from string.
JavaScript
let text = "Hello Good morning!. Welcome to maketechstuff.com";
let matches = text.match(/e/);
document.write(matches);
// Output:
// e
Search for value which is not in the string. (Will return null).
JavaScript
let text = "Hello Good morning!. Welcome to maketechstuff.com";
let matches = text.match(/p/);
document.write(matches);
// Output:
// null
Global search for a value.
JavaScript
let text = "Hello Good morning!. Welcome to maketechstuff.com";
let matches = text.match(/e/g);
document.write(matches);
document.write("<br>");
document.write("No. of letter <b>e</b> is: ", matches.length);
// Output:
// e,e,e,e,e
// No. of letter e is: 5
Example 2: Find words in a string.
JavaScript
let text = "Hello Good, Good, Good morning!. Welcome to maketechstuff.com";
let matches = text.match(/Good/);
document.write(matches);
// Output:
// Good
Global search.
JavaScript
let text = "Hello Good, Good, Good morning!. Welcome to maketechstuff.com";
let matches = text.match(/Good/g);
document.write(matches);
// Output:
// Good,Good,Good
So that is how the JavaScript match() method works. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.