外部替换功能不起作用

External replace function not working

为什么我必须将替换函数放在 str.replace 语句中?

这很好用:

str = str.replace(/&|<|>|"|'/g, function replacer(match) {
switch (match) {
  case "&":
    return "&amp;";
  case "<":
    return "&lt;";
  case ">":
    return "&gt;";
  case '"':
    return "&quot;";
  case "'":
    return "&apos;";
}
});

这不起作用,返回 "Reference error: match is not defined":

str = str.replace(/&|<|>|"|'/g, replacer(match));

function replacer(match) {
switch (match) {
  case "&":
    return "&amp;";
  case "<":
    return "&lt;";
  case ">":
    return "&gt;";
  case '"':
    return "&quot;";
  case "'":
    return "&apos;";
}
}

为什么我不能将 replacer() 作为外部函数调用?传递参数对于其他函数来说是一件轻而易举的事,但在这种情况下 - 从 str.replace 语句中。只是好奇,如果允许好奇的话。此外,这让我很烦...谢谢!

(在发布前到处搜索并反复搜索答案)

这样称呼它:

str = str.replace(/&|<|>|"|'/g, replacer);

意味着你传递的是函数,而不是函数调用结果。

您的回调函数应在使用前创建

function replacer(match) {
    switch (match) {
      case "&":...
    }
}
str = str.replace(/&|<|>|"|'/g, replacer(match));