In this post we will have an in-depth discussion about the match() method; We will start off by looking at the syntax of the match() method:
String is the variable in which we are searching and myexpression is the expression we are searching for.
How does the match() method work
Note: The browser console is used for the demonstration of examples in this article.
The match method returns only the first occurrence of the regular expression inside the string. If we need to check for multiple occurrences then we will need to add the g modifier. The g modifier is a global search modifier that searches the expression at all instances. This returns all the matched elements. If we don’t put this modifier then only the first match will be returned:
We can also use the i modifier with the match method as well. This performs case insensitive matching. In simple words, the match method by default performs a case sensitive search but when we use the i modifier it ignores case sensitivity.
The match method returns null if no match is found:
If we do not give any parameter the match method then it returns the array object containing an empty string:
Using special characters in regExp
We can use different special characters in our regular expressions to carry out more complex searches. The \d sign can be used to search for the first digit in the regular expression:
If we want to get all of the digits present in the string:
The \D sign will output an array of object that contains every character that the /d sign ignores:
A character followed by the $ sign can be used to check whether that is the last character of the given string:
Difference between the match and search methods
The search method searches for the given parameter, if found, it returns the index of that expression in the string whereas the match method returns the expression inside an array object:
console.log('match() method: ' + str.match('and'));
console.log('search() method: ' + str.search('and'));
If the match is not found then the search method returns -1 whereas the match() method returns null: