Check if a value is a regular expression in JavaScript
Beginner · 4 min read
Many functions accept either a plain string or a regular expression. replace and split are two built-in examples: give them text and they look for that exact text, give them a pattern and they match the pattern. If you write a function like that yourself, the first thing it has to do is check which one it was given.
In this tutorial you will write isRegExp. Then you will see why regular expressions are worth checking for: one flag makes them remember things between calls. You should have seen a regular expression before, even a simple one like /a/.
Two ways to write a regular expression
A regular expression (regex for short) is a pattern for matching text. You can write one between slashes, which is called a literal, or build one from a string with new RegExp(...):
const literal = /LAG-\d{3}-[A-Z]{2}/;
const built = new RegExp('LAG-\\d{3}-[A-Z]{2}');
console.log(literal.source === built.source); // true
console.log(literal.test('LAG-441-XA')); // true
console.log(built.test('LAG-441-XA')); // true
Both make the same kind of object. .source is the pattern text, and it matches. The string version needs \\d instead of \d, because inside a string a backslash has to be doubled to stay a backslash.
The constructor is useful when the pattern comes from somewhere else, like a search box.
Flags
Letters after the closing slash are flags. They change how the pattern matches. i ignores upper and lower case, and g (global) means "find every match, not just the first". You can read them back:
console.log(/a/gi.flags); // gi
console.log(/a/g.global); // true
console.log(/a/.global); // false
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 Is the value a regular expression?
easyDetect a RegExp, whether written as /x/ or built with new RegExp('x'). Then note the stateful trap that makes regexes worth checking for.
Stuck? Three hints, smallest first
- 1. The literal form and the constructor form produce the same kind of object.
- 2.
instanceof RegExpworks; the tag check also works and crosses realms. - 3. A regex with the
gflag remembers its position inlastIndexbetween calls.
Step 1: the tag check
typeof isn't enough, because it says 'object' for a regex, just like for an array. The tag check is more specific. Object.prototype.toString.call(v) describes a regex as '[object RegExp]', and .slice(8, -1) keeps the middle word:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
const isRegExp = (v) => tag(v) === 'RegExp';
console.log(typeof /x/); // object
console.log(isRegExp(/x/)); // true
console.log(isRegExp(new RegExp('x'))); // true
console.log(isRegExp(new RegExp(''))); // true
console.log(isRegExp('/abc/')); // false
console.log(isRegExp({})); // false
console.log(isRegExp(null)); // false
The string '/abc/' looks like a regex, but it is just text with slashes in it.
literal instanceof RegExp also works for values made in the same page. The tag check has one extra strength: it still works for values that come from another window or iframe, which have their own copy of RegExp.
Step 2: the g flag remembers
Here is the reason regexes deserve care. A regex with the g flag keeps a position called lastIndex. Each successful .test() moves it forward, and the next call starts searching from there:
const global = /a/g;
console.log(global.test('banana'), global.lastIndex); // true 2
console.log(global.test('banana'), global.lastIndex); // true 4
console.log(global.test('banana'), global.lastIndex); // true 6
console.log(global.test('banana'), global.lastIndex); // false 0
'banana' has an a at positions 1, 3 and 5. After each match, lastIndex points just past it. The fourth call starts at position 6, finds nothing, returns false and resets lastIndex to 0.
So the same regex, given the same text four times, answered true, true, true, false.
Step 3: why that is a bug
Imagine a validator kept in one constant and used for every form field:
const hasDigit = /\d/g;
console.log(hasDigit.test('a1')); // true
console.log(hasDigit.test('b2')); // false
'b2' clearly has a digit. But the first call left lastIndex at 2, so the second call started searching at position 2, which is past the end of 'b2'.
Step 4: two fixes
The simplest fix: leave out the g flag when you only want a yes or no. A regex without it always starts from the beginning:
const hasDigit = /\d/;
console.log(hasDigit.test('a1'), hasDigit.test('b2')); // true true
const hasDigitGlobal = /\d/g;
hasDigitGlobal.test('a1');
hasDigitGlobal.lastIndex = 0;
console.log(hasDigitGlobal.test('b2')); // true
If you need g for other work, set lastIndex back to 0 before each new test.
The full solution
The panel has isRegExp, the same pattern written both ways, and the banana demonstration. Press Run to see the tags, the lastIndex values and the checks.
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
const isRegExp = (v) => tag(v) === 'RegExp';
const literal = /LAG-\d{3}-[A-Z]{2}/;
const built = new RegExp('LAG-\\d{3}-[A-Z]{2}');
console.log('literal :', literal, ' tag:', tag(literal));
console.log('constructed:', built, ' tag:', tag(built));
console.log('same source?', literal.source === built.source);
console.log('--- the trap: a /g regex keeps state between calls ---');
const global = /a/g;
console.log('first test("banana"):', global.test('banana'), 'lastIndex now', global.lastIndex);
console.log('second test("banana"):', global.test('banana'), 'lastIndex now', global.lastIndex);
console.log('third test("banana"):', global.test('banana'), 'lastIndex now', global.lastIndex);
console.log('fourth test("banana"):', global.test('banana'), '<- false, and it reset');
console.log('a non-global regex is stateless:', /a/.test('banana'), /a/.test('banana'));
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a regex literal', isRegExp(literal), true);
test('a constructed regex', isRegExp(built), true);
test('an empty one', isRegExp(new RegExp('')), true);
test('a string that looks like one is not', isRegExp('/abc/'), false);
test('an object is not', isRegExp({}), false);
test('null is not', isRegExp(null), false);
test('a function is not', isRegExp(() => {}), false);
test('instanceof agrees for same-realm values', literal instanceof RegExp, true);
test('both forms have the same source', literal.source === built.source, true);
test('and both match the same text', literal.test('LAG-441-XA') === built.test('LAG-441-XA'), true);
test('flags are readable', /a/gi.flags, 'gi');
test('and the global flag is visible', /a/g.global, true);
test('a fresh non-global regex starts at 0', /a/.lastIndex, 0);
test('a global regex advances lastIndex after a match', (() => { const r = /a/g; r.test('banana'); return r.lastIndex; })(), 2);
test('so repeated tests on the same string eventually fail', (() => { const r = /a/g; return [r.test('banana'), r.test('banana'), r.test('banana'), r.test('banana')]; })(), [true, true, true, false]);
test('while a non-global one always agrees with itself', [/a/.test('banana'), /a/.test('banana')], [true, true]);
Detecting a regex is easy; the reason to care is the g flag. A global regex stores a cursor in lastIndex, so calling .test() on the same string four times gives true, true, true, false — the assertion above pins that down. A regex reused across calls, or stored in a module-level constant, will therefore give different answers on identical input. Either drop the g flag when using .test(), or reset lastIndex yourself.
Common mistakes
- Checking with
typeof v === 'object'. That is alsotruefor arrays, dates andnull. Use the tag check orinstanceof RegExp. - Writing
new RegExp('\d')with one backslash. Inside a string\dis justd. Write'\\d'. - Reusing a
/gregex with.test(). It rememberslastIndex, so identical input can give different answers. Drop thegor resetlastIndex.
Try it yourself
- Write
toRegExp(p)that returnspif it is a regex and otherwisenew RegExp(p). - Store
/a/gin a constant, call.test('banana')on it four times in a loop, and printlastIndexafter each call. - Write
countMatches(text, re)that usestext.match(re)with agregex and returns how many matches it found.