正则表达式的 typeof

发布于 2024-10-05 16:11:34 字数 377 浏览 10 评论 0原文

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

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

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

这可能吗?

谢谢!

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

obj.constructor.name === "RegExp"

或者

obj instanceof RegExp

这两种方法有什么主要优点/缺点吗?

再次感谢!

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"

Is this possible?

Thanks!

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

obj.constructor.name === "RegExp"

or

obj instanceof RegExp

Any major pros/cons to either method?

Thanks again!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

罗罗贝儿 2024-10-12 16:11:34

您可以使用 instanceof 运算符:

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 运算符,这可能是最好的选择对于这个问题。

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

You can use instanceof operator:

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

In fact, that is almost the same as:

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

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.

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

懒的傷心 2024-10-12 16:11:34
alert( Object.prototype.toString.call( t ) ); // [object RegExp]

这是规范中提到的获取对象类的方式。

来自ECMAScript 5,第 8.6.2 节对象内部属性和方法

[[Class]] 内部属性的值是由本规范为每种内置对象定义的。宿主对象的 [[Class]] 内部属性的值可以是任何字符串值,除了“Arguments”、“Array”、“Boolean”、“Date”、“Error”、“Function”、 “JSON”、“数学”、“数字”、“对象”、“正则表达式”和“字符串”。 [[Class]] 内部属性的值在内部用于区分不同类型的对象。请注意,除了通过 Object.prototype.toString(参见 15.2.4.2)之外,本规范没有为程序提供任何访问该值的方法。

RegExp 是规范中第 15.10 节 RegExp(RegularExpression)Objects 中定义的一类对象:

RegExp 对象包含正则表达式和关联的标志。

alert( Object.prototype.toString.call( t ) ); // [object RegExp]

This is the way mentioned in the specification for getting the class of object.

From ECMAScript 5, Section 8.6.2 Object Internal Properties and Methods:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).

A RegExp is a class of object defined in the spec at Section 15.10 RegExp(RegularExpression)Objects:

A RegExp object contains a regular expression and the associated flags.

演出会有结束 2024-10-12 16:11:34

尝试一下 .constructor 属性:

> /^foo(bar)?$/i.constructor
function RegExp() { [native code] }
> /^foo(bar)?$/i.constructor.name
"RegExp"
> /^foo(bar)?$/i.constructor == RegExp
true

Give the .constructor property a whirl:

> /^foo(bar)?$/i.constructor
function RegExp() { [native code] }
> /^foo(bar)?$/i.constructor.name
"RegExp"
> /^foo(bar)?$/i.constructor == RegExp
true
欲拥i 2024-10-12 16:11:34

来自 underscore.js

// Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };

From underscore.js

// Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };
客…行舟 2024-10-12 16:11:34

在谷歌浏览器中工作:

x = /^foo(bar)?$/i;
x == RegExp(x); // true
y = "hello";
y == RegExp(y); // false

Works in google chrome:

x = /^foo(bar)?$/i;
x == RegExp(x); // true
y = "hello";
y == RegExp(y); // false
往昔成烟 2024-10-12 16:11:34

“Regexp”不是原生 Javascript 类型。上面的大多数答案告诉您如何完成任务,但没有告诉您原因。这是原因

"Regexp" is not a native Javascript type. Most of the above answers tell you how to accomplish your task, but not why. Here's why.

锦爱 2024-10-12 16:11:34

没有绝对的方法来检查这一点,到目前为止最好的答案是,

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

但这种方法有一个缺点,那就是如果正则表达式对象来自另一个窗口,它将返回 false。

There is no absolute way of checking this, so far the best answer is

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

but there is one down side to this approach and that's it will return false if the regular expression object is commeing from an other window.

荒芜了季节 2024-10-12 16:11:34

这里有两种方法:

/^\/.*\/$/.test(/hi/) /* test regexp literal via regexp literal */
/^\/.*\/$/.test(RegExp("hi") ) /* test RegExp constructor via regexp literal */
RegExp("^/" + ".*" + "/$").test(/hi/) /* test regexp literal via RegExp constructor */
RegExp("^/" + ".*" + "/$").test(RegExp("hi") ) /* test RegExp constructor via RegExp constructor */ 

delete RegExp("hi").source /* test via deletion of the source property */
delete /hi/.global /* test via deletion of the global property */
delete /hi/.ignoreCase /* test via deletion of the ignoreCase property */
delete RegExp("hi").multiline /* test via deletion of the multiline property */
delete RegExp("hi").lastIndex /* test via deletion of the lastIndex property */

如果字符串文字由正则表达式反斜杠分隔符分隔,则正则表达式自检将失败。

如果 Object.sealObject.freeze 在用户定义的对象上运行,并且该对象也具有上述所有属性,则 delete > 语句将返回误报。

参考

Here are two ways:

/^\/.*\/$/.test(/hi/) /* test regexp literal via regexp literal */
/^\/.*\/$/.test(RegExp("hi") ) /* test RegExp constructor via regexp literal */
RegExp("^/" + ".*" + "/$").test(/hi/) /* test regexp literal via RegExp constructor */
RegExp("^/" + ".*" + "/$").test(RegExp("hi") ) /* test RegExp constructor via RegExp constructor */ 

delete RegExp("hi").source /* test via deletion of the source property */
delete /hi/.global /* test via deletion of the global property */
delete /hi/.ignoreCase /* test via deletion of the ignoreCase property */
delete RegExp("hi").multiline /* test via deletion of the multiline property */
delete RegExp("hi").lastIndex /* test via deletion of the lastIndex property */

If a string literal is delimited by the regexp backslash delimiter, the regexp self test will fail.

If Object.seal or Object.freeze are run on a user-defined object, and that object also has all of the aforementioned properties, the delete statement will return a false positive.

References

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文