Javascript regex match: Check If String Matches Regex
JavaScript String match() method is used to search a string for a match against any regular expression and will return the match as an array if any match found.
Javascript regex match
JavaScript match() method searches a string for a match versus a regular expression, and returns the matches, as the array. To use a javascript regex match, use a string match() method.
Syntax
string.match(regexp)
Parameters
regexp: It is a required parameter, and it is a value to search for, as a regular expression.
Return Value
The match() method returns null if it does not find any match otherwise returns an array.
Example
// app.js let str = "Here is your winner, brock lesnar"; let res = str.match(/bro/gi); console.log(res);
Output
node app [ 'bro' ]
In this example, we are checking bro string against the main string, and it found the match and returns the array containing that item.
Regular expressions are patterns used to match the character combinations in strings. In JavaScript, regular expressions are also objects. Here, our pattern is a bro and using match() function, and we are checking that pattern against our input string.
Global search in regex
To search global in the string using regex, use match() method and pass “g” flag.
// app.js let str = "Well done brock! Well done"; let res = str.match(/Well/g); console.log(res);
Output
node app [ 'Well', 'Well' ]
In this example, we are searching globally for a Well pattern, and it finds two times in the string. Here “g” flag suggests that the regular expression should be tested against all possible matches in the string.
Python regex match: case-sensitive
If you don’t pass the case sensitivity flag “i” explicitly, then it will return null. By default, the string match() method does not check case sensitive match. If you want to check a case-sensitive match, then you have to pass “i” flag explicitly.
// app.js let str = "Well done brock! Well done"; let res = str.match(/well/g); console.log(res);
Output
null
Our pattern is well, and our input string contains Well. So, there is a mismatch between the input string and pattern. That is why it returns null.
If you pass the “i” flag in the regex, then it will return true.
// app.js let str = "Well done brock! Well done"; let res = str.match(/well/gi); console.log(res);
Output
[ 'Well', 'Well' ]
Here “i” flag helps to find the case-sensitive match in the given string.
Conclusion
If the regex doesn’t have flag g, then it returns the first match as an array.
If the regex has flag g, then it returns the array of all matches as strings.
If there are no matches found using match() method, no matter if there’s flag g or not, the null is returned.
That is it for JavaScript regex match example.