有没有办法检测JavaScript对象是否是正则表达式?
例如,我想这样做:
var t = /^foo(bar)?$/i;
alert(typeof t); //I want this to return "regexp"
这个是可能的吗?
谢谢!
编辑:感谢您的回答。看起来我有两个非常好的选择:
obj.constructor.name === "RegExp"
或
obj instanceof RegExp
这两种方法都有什么主要的优缺点吗?
再次感谢!
发布于 2010-12-03 04:05:15
让.constructor
属性转一转:
> /^foo(bar)?$/i.constructor
function RegExp() { [native code] }
> /^foo(bar)?$/i.constructor.name
"RegExp"
> /^foo(bar)?$/i.constructor == RegExp
true
发布于 2010-12-03 04:05:23
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
发布于 2010-12-03 04:04:54
在google chrome中工作:
x = /^foo(bar)?$/i;
x == RegExp(x); // true
y = "hello";
y == RegExp(y); // false
https://stackoverflow.com/questions/4339288
复制相似问题