Explain Codes LogoExplain Codes Logo

Check whether a string matches a regex in JS

javascript
regex-engineering
javascript-best-practices
performance
Nikita BarsukovbyNikita Barsukov·Jan 4, 2025
TLDR

Here is a quick way to check if a string matches a regex using JavaScript's test():

const isMatch = /pattern/.test('string to test'); // Returns true or false // console.log(isMatch ? "You've Got Match!" : "So close, yet so far...")

When you seek to find all matches, use match():

const matches = 'string to test'.match(/pattern/); // Returns ['match'] or null // console.log(matches ? `Match Count: ${matches.length}` : "Oops! No matches")

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.

/^pattern$/.test('entire string'); // true or false // console.log(/^pattern$/.test('entire string') ? "Can't touch this 😎" : "Doh! 😔")

To make your checks case-insensitive, use the i flag:

const regex = new RegExp('pattern', 'i'); const valid = regex.test('String to Test'); // true or false // console.log(valid ? "You're the chosen one!" : "Not the match we're looking for...")

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:

const datePattern = /(\d{4})-(\d{2})-(\d{2})/; const [, year, month, day] = '2023-04-01'.match(datePattern); // console.log(`Year: ${year}, Month: ${month}, Day: ${day}`);

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.

const globalRegex = /pattern/g; globalRegex.test('string'); // true globalRegex.test('string'); // false - unexpected! // console.log(globalRegex.test('string') ? "You found Waldo!" : "Where is Waldo?")

Resources to win the Regex Battle

  1. RegExp - JavaScript | MDN — an extensive guide on JavaScript Regular Expressions.
  2. How to use JavaScript Regular Expressions — a comprehensive guide to understanding and implementing regex in JavaScript.
  3. JavaScript RegExp Reference — a complete reference for the RegExp object and its methods.
  4. Regular Expressions :: Eloquent JavaScript — a useful section for learning JavaScript regex through examples.
  5. Patterns and flags — a simple, precise guide on the test() method with examples.
  6. regex101: build, test, and debug regex — an awesome interactive tool for testing regular expressions.
  7. regex.test() only works every other time - Stack Overflow — clarifies a common problem when using test() in JavaScript.