开发者

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

开发者 https://www.devze.com 2023-04-09 22:33 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: typeof for RegExp I have a routine that is testing to see if an object matches given criteria.
This question already has answers here: Closed 11 years ago.

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?


how about

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

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

>>true
0

精彩评论

暂无评论...
验证码 换一张
取 消