Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an object is a RegExp object? [duplicate]

Possible Duplicate:
typeof for RegExp

I have a routine that is testing to see if an object matches given criteria.

testForMatch(objectToTest, matchCriteria) {
    // all my testing logic here.
}

The parameter matchCriteria is an object that could look like this, for example:

{
    'size'     : "large",
    'color'    : /(blue|red)/
}

This matchCriteria in the above example will be used to test if objectToTest has an attribute size with value "large", and an attribute color with value of either "blue" or "red".

So matchCriteria has property/attribute names that will be sought in objectToTest with the goal of matching the values of the properties. Or, if a regex is given as the value (as in the case of color above) the property in objectToTest will be RegExp.test()'ed against the given regex.

But in order to treat the matchCriteria properly in testForMatch(), I need to be able to tell if the value of an attribute in matchCriteria is a string or a RegExp object.

My question is, how can I detect if the value of an attribute is a RegExp object?

like image 303
Jonathan M Avatar asked Sep 30 '11 15:09

Jonathan M


1 Answers

how about

var o = {
    'size' : "large",
    'color': /(blue|red)/
}

console.log( o['color'] instanceof RegExp )

>>true
like image 61
Alex K. Avatar answered Sep 27 '22 16:09

Alex K.