【问题标题】:JavaScript RegExp evaluationJavaScript 正则表达式评估
【发布时间】:2019-02-22 22:55:05
【问题描述】:

我正在查看一些代码并找到了第一行。当我发现如果我尝试以保持语义相同的方式使其更简单时,我开始感到困惑,它就不一样并且结果会发生变化。谁能向我解释这种行为?

RegExp("\x3c").test(function(){return"\x3c"}) //false
RegExp("<").test(function(){return"<"})       //true
RegExp("\x3c").test("\x3c")                   //true
RegExp("<").test("<")                         //true

【问题讨论】:

  • 不知道您是否已经知道这一点,但您没有测试前 2 行中的返回字符串。您必须附加 ()

标签: javascript regex evaluation


【解决方案1】:

当您将非字符串传递给.test 时,它会被转换为字符串,而 不会替换函数代码中的任何文字字符。查看前两个函数的字符串化版本:

console.log(function(){return"\x3c"}.toString());
console.log(function(){return"<"}.toString());

因为第一个函数的源代码有"\x3c",所以字符串化的版本也包含它——"\x3c" 不会被'&lt;' 替换。虽然"\x3c" === '&lt;',但在对函数进行字符串化时,解释器并不会为你进行替换。

当您将"\x3c" 传递给new RegExp 时(或传递给任何函数,例如第三个测试),它变成'&lt;'

console.log("\x3c");
console.log(RegExp("\x3c"));

所以,你原来的代码相当于:

/</.test(String.raw`function(){return"\x3c"}`); //false
/</.test(String.raw`function(){return"<"}`);    //true
/</.test("<");                        //true
/</.test("<");                        //true

【讨论】:

    【解决方案2】:

    test 默认将字符串作为参数,任何其他类型都将转换为字符串

    const a = function(val) {
      return val
    }
    console.log(a)
    const res = RegExp("\x3c").test(a) //false
    const res2 = RegExp("<").test(a) //false
    
    console.log(res, res2)
    
    const b = function() {
      return "<"
    }
    
    const res3 = RegExp("<").test(b)
    
    console.log(res3) //true

    result false 两个原因“function(val){return val}”不包含任何匹配项

    res3 是真的原因"function(){return '&lt;'}" 匹配"&lt;"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2012-02-02
      相关资源
      最近更新 更多