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!


Solution 1:

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)).

Solution 2:

alert( Object.prototype.toString.call( t ) ); // [object RegExp]

This is the way mentioned in the specification for getting the class of object.

From ECMAScript 5, Section 8.6.2 Object Internal Properties and Methods:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).

A RegExp is a class of object defined in the spec at Section 15.10 RegExp(RegularExpression)Objects:

A RegExp object contains a regular expression and the associated flags.

Solution 3:

Give the .constructor property a whirl:

> /^foo(bar)?$/i.constructor
function RegExp() { [native code] }
> /^foo(bar)?$/i.constructor.name
"RegExp"
> /^foo(bar)?$/i.constructor == RegExp
true

Solution 4:

From underscore.js

// Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };

Solution 5:

Works in google chrome:

x = /^foo(bar)?$/i;
x == RegExp(x); // true
y = "hello";
y == RegExp(y); // false