typeof for RegExp [英] typeof for RegExp

查看:157
本文介绍了typeof for RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有反正检测JavaScript对象是否是正则表达式?

Is there anyway to detect if a JavaScript object is a regex?

例如,我想这样做:

var t = /^foo(bar)?$/i;
alert(typeof t); //I want this to return "regexp"

这是否可能?

谢谢!

编辑:感谢所有的答案。看来我有两个很好的选择:

Thanks for all the answers. It seems I have two very good choices:

obj.constructor.name === "RegExp"

obj instanceof RegExp

这两种方法的主要优点/缺点?

Any major pros/cons to either method?

再次感谢!

推荐答案

您可以使用 instanceof 运算符:

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

事实上, em> 相同:

In fact, that is almost the same as:

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

请记住由于正则表达式不是原始数据类型,不可能使用 typeof 运算符,它可以

Keep in mind that as Regex is not a primitive data type, it is not possible to use typeof operator which could be the best option for this question.

但是你可以使用上面的这个技巧或者像 杜克类型检查,例如,检查此类对象是否具有任何重要的方法或属性,或通过其内部类值(通过使用 {}。toString.call(instaceOfMyObject))。

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)).

这篇关于typeof for RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆