Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof for RegExp

Is there anyway to detect if a JavaScript object is a regex?

For example, I would like to do something like this:

var t = /^foo(bar)?$/i;
alert(typeof t); //I want this to return "regexp"

Is this possible?

Thanks!

EDIT: Thanks for all the answers. It seems I have two very good choices:

obj.constructor.name === "RegExp"

or

obj instanceof RegExp

Any major pros/cons to either method?

Thanks again!

like image 995
tau Avatar asked Oct 02 '22 07:10

tau


People also ask

What type is regex?

The Regexp data type The data type of regular expressions is Regexp . By default, Regexp matches any regular expression value. If you are looking for a type that matches strings which match arbitrary regular expressions, see the Pattern type.

Is regex a type in JavaScript?

A regular expression is a type of object. It can be either constructed with the RegExp constructor or written as a literal value by enclosing a pattern in forward slash ( / ) characters. Both of those regular expression objects represent the same pattern: an a character followed by a b followed by a c.

What is typeof for a class?

In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. Syntax: typeof operand.


1 Answers

You can use instanceof operator:

var t = /^foo(bar)?$/i;
alert(t instanceof RegExp);//returns true

In fact, that is almost the same as:

var t = /^foo(bar)?$/i;
alert(t.constructor == RegExp);//returns true

Keep in mind that as RegExp is not a primitive data type, it is not possible to use typeof operator which could be the best option for this question.

But you can use this trick above or others like duck type checking, for example, checking if such object has any vital methods or properties, or by its internal class value (by using {}.toString.call(instaceOfMyObject)).

like image 242
Cleiton Avatar answered Oct 11 '22 20:10

Cleiton