Prefer Testing Regular Expressions to Matching Them
Something that is often done in Front-End development is checking if a string matches some pattern, or contains some substring. The
lastIndexOf. (Of course, if you want to check that a string exactly matches another string, nothing beats a plain old
=== operator.) The alternative to using the
String methods is to use
test method. There are no performance hits for doing this compared to both
search as they implicitly convert their arguments to regular expressions.
However, the main benefit from using
test instead of
match is robustness. The string that you are testing is usually an unreliable variable: it comes from user input or an api response. If that variable should happen to be
null instead of a string, then
match will throw an error at runtime. However, if you used
test instead, then checking a possibly undefined or null value will just return false. When you are writing code to check a string, you are generally hard-coding the regex, so it is known to exist at runtime, whereas the string is not.
What if the regex is built at runtime? Suppose that you had written this code to check if a user had an email account with you:
How could you write that as a regex?
The same way that
match does implicitly: by using the
RegExpobject rather than creating a regex literal.
If you want to eliminate runtime errors from calling
match on null or undefined variables, start writing your regex checks with the regex first, using
test. It’s much more robust and still easy to read.