正则表达式的类型 [英] typeof for RegExp

查看:22
本文介绍了正则表达式的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何要检测 JavaScript 对象是否为正则表达式?

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

例如,我想做这样的事情:

For example, I would like to do something like this:

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 运算符:

You can use instanceof operator:

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

事实上,这几乎等同于:

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

请记住,as RegExp 不是 原始数据类型,不可能使用 typeof 运算符,它可以 成为这个问题的最佳选择.

Keep in mind that as RegExp 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)).

这篇关于正则表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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