JavaScript 正则表达式评估

JavaScript RegExp evaluation

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

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

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

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

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

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

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

因此,您的原始代码相当于:

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

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

结果 false 两个原因 "function(val){return val}" 不包含任何匹配项

res3 为真,因为 "function(){return '<'}" 匹配 "<"