javascript - typeof for RegExp -
is there anyway detect if javascript object regex?
for example, this:
var t = /^foo(bar)?$/i; alert(typeof t); //i want return "regexp"
is possible?
thanks!
edit: answers. seems have 2 choices:
obj.constructor.name === "regexp"
or
obj instanceof regexp
any major pros/cons either method?
thanks again!
you can use instanceof operator:
var t = /^foo(bar)?$/i; alert(t instanceof regexp);//returns true
in fact, almost same as:
var t = /^foo(bar)?$/i; alert(t.constructor == regexp);//returns true
keep in mind regex not primitive data type, not possible use typeof
operator be best option question.
but can use trick above or others duck type checking, example, checking if such object has vital methods or properties, or internal class value(by using {}.tostring.call(instaceofmyobject)
).
Comments
Post a Comment