Javascript 正则表达式的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4339288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typeof for RegExp
提问by tau
Is there anyway to detect if a JavaScript object is a regex?
无论如何要检测 JavaScript 对象是否是正则表达式?
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!
再次感谢!
回答by Cleiton
You can use instanceofoperator:
您可以使用instanceof运算符:
var t = /^foo(bar)?$/i;
alert(t instanceof RegExp);//returns true
In fact, that is almostthe same as:
事实上,这几乎等同于:
var t = /^foo(bar)?$/i;
alert(t.constructor == RegExp);//returns true
Keep in mind that as RegExpis not a primitive data type, it is not possible to use typeof
operator which could be the best optionfor this question.
请记住,由于RegExp不是原始数据类型,因此不可能使用typeof
可能是此问题最佳选择的运算符。
But you can use this trick above or others like duck typechecking, for example, checking if such object has any vital methods or properties, or by its internal class value(by using {}.toString.call(instaceOfMyObject)
).
但是你可以使用上面的这个技巧或其他类似duck类型检查的技巧,例如,检查这样的对象是否有任何重要的方法或属性,或者通过它的内部类值(通过使用{}.toString.call(instaceOfMyObject)
)。
回答by user113716
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:
来自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).
[[Class]] 内部属性的值由本规范为每种内置对象定义。宿主对象的 [[Class]] 内部属性的值可以是任何字符串值,除了“Arguments”、“Array”、“Boolean”、“Date”、“Error”、“Function”、“JSON”之一、“数学”、“数字”、“对象”、“RegExp”和“字符串”。[[Class]] 内部属性的值在内部用于区分不同种类的对象。请注意,除了通过 Object.prototype.toString(见 15.2.4.2)之外,本规范没有为程序提供任何访问该值的方法。
A RegExp is a class of object defined in the spec at Section 15.10 RegExp(RegularExpression)Objects:
RegExp 是第 15.10 节 RegExp(RegularExpression)Objects规范中定义的一类对象:
A RegExp object contains a regular expression and the associated flags.
RegExp 对象包含一个正则表达式和相关的标志。
回答by John Kugelman
Give the .constructor
property a whirl:
试一试.constructor
物业:
> /^foo(bar)?$/i.constructor
function RegExp() { [native code] }
> /^foo(bar)?$/i.constructor.name
"RegExp"
> /^foo(bar)?$/i.constructor == RegExp
true
回答by Sean Vieira
From underscore.js
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
回答by werehuman
Works in google chrome:
适用于谷歌浏览器:
x = /^foo(bar)?$/i;
x == RegExp(x); // true
y = "hello";
y == RegExp(y); // false
回答by Visionary Software Solutions
回答by Iman Mohamadi
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.
但是这种方法有一个缺点,那就是如果正则表达式对象来自另一个窗口,它将返回 false。
回答by Paul Sweatte
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.
如果Object.seal
或Object.freeze
在用户定义的对象上运行,并且该对象还具有上述所有属性,则该delete
语句将返回误报。
References
参考