typeof for RegExp

JavascriptRegexConstructorInstanceofTypeof

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

Works in google chrome:

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

Solution 6 - Javascript

"Regexp" is not a native Javascript type. Most of the above answers tell you how to accomplish your task, but not why. Here's why.

Solution 7 - Javascript

There is no absolute way of checking this, so far the best answer is

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

but there is one down side to this approach and that's it will return false if the regular expression object is commeing from an other window.

Solution 8 - Javascript

Here are two ways:

/^\/.*\/$/.test(/hi/) /* test regexp literal via regexp literal */
/^\/.*\/$/.test(RegExp("hi") ) /* test RegExp constructor via regexp literal */
RegExp("^/" + ".*" + "/$").test(/hi/) /* test regexp literal via RegExp constructor */
RegExp("^/" + ".*" + "/$").test(RegExp("hi") ) /* test RegExp constructor via RegExp constructor */ 

delete RegExp("hi").source /* test via deletion of the source property */
delete /hi/.global /* test via deletion of the global property */
delete /hi/.ignoreCase /* test via deletion of the ignoreCase property */
delete RegExp("hi").multiline /* test via deletion of the multiline property */
delete RegExp("hi").lastIndex /* test via deletion of the lastIndex property */

If a string literal is delimited by the regexp backslash delimiter, the regexp self test will fail.

If Object.seal or Object.freeze are run on a user-defined object, and that object also has all of the aforementioned properties, the delete statement will return a false positive.

References

Solution 9 - Javascript

I was looking for typeof regex because I tried use it in type definition for TypeScript props on a function.

Then I do the next:

const RegexType = /$/;

type paramProps = {
  regexParam: typeof RegexType;
}

You can test here:

const RegexType = /$/;
const t = /^foo(bar)?$/i;

console.log(typeof t == typeof RegexType) //true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontauView Question on Stackoverflow
Solution 1 - JavascriptCleitonView Answer on Stackoverflow
Solution 2 - Javascriptuser113716View Answer on Stackoverflow
Solution 3 - JavascriptJohn KugelmanView Answer on Stackoverflow
Solution 4 - JavascriptSean VieiraView Answer on Stackoverflow
Solution 5 - JavascriptVladimir LagunovView Answer on Stackoverflow
Solution 6 - JavascriptVisionary Software SolutionsView Answer on Stackoverflow
Solution 7 - JavascriptIman MohamadiView Answer on Stackoverflow
Solution 8 - JavascriptPaul SweatteView Answer on Stackoverflow
Solution 9 - JavascriptEsteban CabreraView Answer on Stackoverflow