【问题标题】:Detect If Variable Is A Pattern [duplicate]检测变量是否为模式[重复]
【发布时间】:2018-02-14 08:45:48
【问题描述】:

我无法找到检测变量是否为正则表达式的方法。但我还需要弄清楚它是否是一个对象,所以我不能使用 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);
}

【问题讨论】:

    标签: javascript regex if-statement detect legacy


    【解决方案1】:

    有很多方法可以做到这一点,它们包括:

    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 我明白了,我刚刚添加了一条评论。
    【解决方案2】:

    您可以使用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);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2013-11-16
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多