Prefer Testing Regular Expressions to Matching Them

Two methods for checking if a string conforms to a pattern

Something that is often done in Front-End development is checking if a string matches some pattern, or contains some substring. The String object in Javascript provides several nice methods to do this: match, search, indexOf, and 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 RegExp's test method. There are no performance hits for doing this compared to both match and 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 undefined or null instead of a string, then match will throw an error at runtime. However, if you used RegExp's 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.

Dynamic Regexes

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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.