检测变量是否为模式
问题描述:
我找不到一种方法来检测变量是否为正则表达式。但我也需要弄清楚它是否是一个对象,所以我不能使用typeof(regex) === 'object'
并依赖它,因为它可能会因为if语句将执行它,就好像它是一个正则表达式。但我希望它也能在传统浏览器中工作。任何帮助将不胜感激。检测变量是否为模式
var regex= /^[a-z]+$/;
//...Some code that could alter the regex variable to become an object variable.
if (typeof(regex) === 'object') {
console.log(true);
}
答
您可以使用instanceOf
var regex= /^[a-z]+$/;
//...Some code that could alter the regex variable to become an object variable.
if (regex instanceof RegExp) {
console.log(true);
}
答
有办法做到这一点,它们包括:
var regex= /^[a-z]+$/;
// constructor name, a string
// Doesn't work in IE
console.log(regex.constructor.name === "RegExp"); // true
// instanceof, a boolean
console.log(regex instanceof RegExp); // true
// constructor, a constructor
console.log(regex.constructor == RegExp); // true
第一个在IE中不起作用。不要测试函数名称。 – Bergi
@Bergi这就是为什么我提到其他方法。 –
但为什么要提到这一切?这只会增加读者阅读答案的机会(特别是首先提到的)。 – Bergi