Often scripts have to process large chunks of data in the form of a string. JavaScript provides a range of possible operations for this purpose. For example, there is a very useful method for searching a specific pattern in your string - match().

This method accepts one parameter which is a regular expression specifying how the substring you are searching for should look like. The returned result would be an array containing the matches.

Notes on using match()

In order to call this method you need to use your string of characters and a regular expression. The latter one should also be represented in a string format. The correct syntax is illustrated below.

const string = 'test';
const array = string.match(/t/);
console.log(array); // logs [ "t" ] 

If you pass a value of a different data type, the JS will try to convert it using the new RegExp() constructor. For example, if you call match (30), the number will be converted into a numeric string and the search will still be performed. The same situation is with null, NaN and Infinity. 

const string = 'He is 30 years old';
const array = string.match(30);
console.log(array[0]); // logs 30

The match() method will return an array of strings as a result. If you don’t pass any parameters to this method, you will get an array containing an empty string in the output. 

Note that in case there are no matches in your string, the returned result would be null instead of an empty array. However, if you desperately need the result to be represented in a form of array, you can write the command as in the example below.

const string = 'test';
const array = string.match(/a/) || [];
console.log(array); // logs []

Keep in mind that the form of the returned array depends on whether your regular expression has the g flag or not. This flag makes your search to be global. Thus, if there is no a g letter in your regex, the match() method will return an array containing the first match only. 

It will also have an index property which has information about the position of the match and an input property containing the string where the search was performed. The following code illustrates this case.

const string = 'test';
const array = string.match(/t/);
console.log(array[0], array[1]); // logs "t undefined"
console.log(array.index); // logs 0

You can see that even though the word ‘test’ contains two t letters, the method returns an array containing one element only, and the index property has the value of 0 which is the index of the first ‘t’ in your string. If you want to find the first match only, you may consider using another option for that purpose - regex.exec(string)

In case if you include the g modifier into your regex, the match() method will return an array of all the found matches. However, the properties such as index and input will not be available in this situation.

const string = 'test';
const array = string.match(/t/g);
console.log(array[0], array[1]); // logs "t t"
console.log(array.index); // logs "undefined"

Examples of match()

Regular expression is a very flexible tool allowing you to easily specify patterns of various kinds. One of the most important flags, the g flag, has been introduced earlier. You can also use the i flag in order to make your search case insensitive. For example, the code below will print all the cases when a letter a, b, c or A, B, C is found.  

const string = 'ABCDEabcde';
const array = string.match(/[a-c]/gi);
console.log(array); // logs "(6) ['A', 'B', 'C', 'a', 'b', 'c']"

There are also some special symbols to indicate the character classes. For example, use \d if you want to match any digit from 0 to 9 or \D if you are looking for any other character different from a digit. In the same way the special character \w allows you to look for any alpha-numerical symbols (both digits and letters) and \W finds any other symbols or spaces.

In order to indicate that you are looking for several symbols going in a row, you can use +. For example, the regex \d+ means that the substring you are looking for may be a digit or several digits. Thus, if you call match(/\d+/g), the method will return an array of all numeric substrings as illustrated in the code below.

const string = '12 plus 5 is equal to 17';
const array = string.match(/\d+/g);
console.log(array); // logs "(3) ['12', '5', '17']"

Some browsers support such a feature as a capturing group. That is some kind of a label that you can give to your match. In order to create such a label you just need to surround its name by ?<…>. For example, let’s create a regular expression for searching certain parts in an operation of division. 

Simply make the first label ?<divident> and follow it by the special symbol indicating any digit from 0 to 9. A plus will mean that the number may consist of one or more digits. You can use the backslash \ in order to mark that the next symbol (/) is not special. Find a divisor and a quotient in the same way.

The following code illustrates the implementation of this case. If you run the match() method with the created regex and print the group property of the returned array, you will get three labels along with the found results.

const string = '12/3=4';
const regex = /(?<divident>\d+)\/(?<divisor>\d+)=(?<quotient>\d+)/;
const array = string.match(regex);

console.log(array.groups);
// logs "{divident: '12', divisor: '3', quotient: '4'}"

Conclusion

The match() method is a very flexible tool for searching a certain substring in a given text. It is capable of looking for a single or multiple matches and returns an array of matches as a result. The use of regular expressions makes this method very comprehensive. However, in some cases, for example, when you need to get the first match only, consider using the regex.exec(string) method instead.