Check whether a string matches a regex in JS
Here is a quick way to check if a string matches a regex using JavaScript's test()
:
When you seek to find all matches, use match()
:
Understanding test()
and match()
In JavaScript, test()
and match()
are the most commonly used string processing methods. test()
returns a boolean value indicating whether or not a pattern exists within a string. On the other hand, match()
returns the matches it found, or null
if none were found.
Keep your regex free from unnecessary capture groups ()
for further clarity and test()
performance.
To make your checks case-insensitive, use the i
flag:
Did someone say performance?
When performance is critical, test()
is your go-to. It's designed solely to confirm the existence (or not) of a matching pattern in a string and hence, significantly faster and memory-efficient. But watch out, test()
can give false results when used with non-string values.
Debugging Regex: a survival guide
Dodging errors often requires understanding regex patterns. Special characters, for instance, need to be escaped with a \
. Understanding these rules can save you countless - perhaps hair-pulling - debug sessions.
Advanced manipulations using match()
When you need to perform manipulations, match()
is a pretty handy tool. It can return a detailed match information that is perfect for extracting and manipulating values. Here's how you can use it in practical situations, like extracting date parts:
Beware of the global flag
If you apply the g
flag for global search with test()
, watch out! Due to the lastIndex
property of regex objects, test()
starts from the index of the last match. This could result in calling test()
every other time on the same string.
Resources to win the Regex Battle
- RegExp - JavaScript | MDN — an extensive guide on JavaScript Regular Expressions.
- How to use JavaScript Regular Expressions — a comprehensive guide to understanding and implementing regex in JavaScript.
- JavaScript RegExp Reference — a complete reference for the RegExp object and its methods.
- Regular Expressions :: Eloquent JavaScript — a useful section for learning JavaScript regex through examples.
- Patterns and flags — a simple, precise guide on the
test()
method with examples. - regex101: build, test, and debug regex — an awesome interactive tool for testing regular expressions.
- regex.test() only works every other time - Stack Overflow — clarifies a common problem when using
test()
in JavaScript.
Was this article helpful?