Checking strings for patterns in JavaScript
Write code deliberately, and pick the right tool for the job
Write code deliberately, and pick the right tool for the job
JavaScript offers us several methods for checking strings for patterns, most notably found on RegExp
and String
objects. This article aims to highlight two methods I see being used for checking strings for patterns, how they might be misused, and how you can use them appropriately.
This article assumes you understand what regular expressions are, how to infer their meaning, and when it’s appropriate to use them.
Problem: Write a function that takes a string and a pattern as its inputs and prints “Pattern Found” if the pattern is found in the string and “Pattern Not Found” otherwise.
Although masked in simplicity and maybe even triviality, developers frequently encounter problems similar to this one — a problem where we must check that a string contains a certain pattern and write code that does one thing when the pattern is found and take another course of action when the pattern is absent from the string. We encounter this problem so often that we develop a solution that sits ready to be pulled out of our left brains at a moment’s notice.
If you write JavaScript and encounter this problem, take a minute to think about which one of the below solutions you are more likely to write. Both solutions produce the same results in every case, but I propose that one is better than the other for this problem.
Solution #1
function testStrForPattern(str, pattern) {
if (str.match(pattern)) {
return console.log("Pattern Found");
}
return console.log("Pattern Not Found");
}
const sentence = "We write JavaScript code for people!";
testStrForPattern(sentence, /javascript|code/i); // Output: "Pattern Found"
testStrForPattern(sentence, /php|web/i); // Output: "Pattern Not Found"
Solution #2
function testStrForPattern(str, pattern) {
if (pattern.test(str)) {
return console.log("Pattern Found");
}
return console.log("Pattern Not Found");
}
const sentence = "We write JavaScript code for people!";
testStrForPattern(sentence, /javascript|code|web/i); // Output: "Pattern Found"
testStrForPattern(sentence, /php|web/i);// Output: "Pattern Not Found"
Pick the right tool for the job
“Pick the right tool for the job” is a sentence we hear a lot in industry, and I suspect many of us really try to abide. I hear this sentence most frequently used when addressing the macro solution to a problem, for example, in using an appropriate software package or in choosing an appropriate software development methodology. Now, I am making the same recommendation to pick the right tool for the job at the micro level (in code), because it matters there too.
String.prototype.match()
str.match(pattern)
If the string matches the expression, it will return anArray
containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches,null
is returned.
RegExp.prototype.test()
pattern.test(str)
Returnstrue
if there is a match between the regular expression and the specified string; otherwise,false
.
The first solution works because if the pattern is found, the returned array will evaluate to true
in the if
statement and false
when null
is return due to the absence on the pattern in the string.
However, match
was not designed to simply and efficiently check if a pattern is found in a string. Anticipating the misuse of match
, the Mozilla Developer Network documents,
If you need to know if a string matches a regular expressionRegExp
, useRegExp.test()
Finally, we can intuit that match
performs slower than test
. Just imagine the extra work being done to build up an array of all the matched substrings as opposed to returning a single value on the first occurrence of a match. Still don’t believe me? Take a look at how much faster test
is than match
here. It’s much faster!
Final words
Use test
to do a simple boolean check for whether or not a pattern exists in a string and match
to build up an array of the matches found in the string. When it comes to solving problems with code, picking the right tool for the job is just as important in the micro as it is in the macro.