[JS-101] RegExp.exec vs String.match

kelly woo
3 min readAug 1, 2021

Validation of form control is critical and most time we check the validity of the content and delete or fix certain characters with Regular Expression(RegExp).

Photo by Clark Van Der Beken on Unsplash

And I’ve seen many codes declaring these RegExp in somewhere of the app and use it over and over with .exec() and .test() or passing this as an argument of the function without any guards.
This article is why it is not a good practice and how it might get you into a trouble.

RegExp.exec vs String.match

Most time exec and match returns identical value in array.
So some might think they are same except the switched order of RegExp and string.

But if you put global flag g at the regular expression instance, it makes a difference on the outcome.

It is because .match() searches all matching parts of the target (if you’d like to get capture group as well, use matchAll) on the other hand.exec() pauses on its first hit and next time it runs from where it paused, hence using exec instead of match in certain cases can save us some performance.

What’s the Trouble then?

Here’s the question, what would be the answer of the second test?

This is the answer.

RegExp.test and RegExp.exec stores lastIndex and calling this method refers to the lastIndex and it tries to match from the lastIndex. This is why the second test returns false.
See the test with the log.

So calling these method updates lastIndex and it schedules a side-effects on the next call which we might not predicted.

Then How should we do?
lastIndex is readable and writable property so you can update it directly by allocating new data.

a.lastIndex = 0;

But I’d prefer to use new instance every time or at least when you use exec|test, check whether this instance is global or not, and guard it like the below.

const regExp = old.global? new RegExp(old, old.flags.replace('g', '')) : old;regExp.test(...)

It is basic, but easy to overlook.
I hope some find this helpful and thanks for reading.
😄

--

--