Javascript .replaceAll() 不是函数类型错误

pyk*_*202 51 javascript typeerror

文档页面:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

let string = ":insertx: :insertx: :inserty: :inserty: :insertz: :insertz:";
let newstring = string.replaceAll(":insertx:", 'hello!');
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到Uncaught TypeError: string.replaceAll is not a function. 也许我误解了原型是什么,但该函数似乎是一个可用的字符串方法。

我正在使用 Chrome。

hev*_*ev1 43

replace与带有 global修饰符的正则表达式一起使用以获得更好的浏览器支持。(查看MDN 上浏览器兼容性表,了解每个浏览器的哪个版本开始支持该replaceAll方法。)

let string = ":insertx: :insertx: :inserty: :inserty: :insertz: :insertz:";
let newstring = string.replace(/:insertx:/g, 'hello!');
console.log(newstring);
Run Code Online (Sandbox Code Playgroud)

对于更通用的解决方案,我们可以转义正则表达式元字符并使用RegExp构造函数。您还可以将该函数添加String.prototype为 polyfill。

(有必要对要替换的字符串进行转义,以便在正则表达式中具有特殊含义的字符将按字面解释,例如.仅指实际的点而不是任何字符。)

//Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function replaceAll(str, match, replacement){
   return str.replace(new RegExp(escapeRegExp(match), 'g'), ()=>replacement);
}

console.log(replaceAll('a.b.c.d.e', '.', '__'));
console.log(replaceAll('a.b.c.d.e', '.', '$&'));
Run Code Online (Sandbox Code Playgroud)

可以在此处找到符合规范的垫片。


Mat*_*ant 36

.replaceAll 将在 Chrome 85 上可用。当前版本是 83。

如果您下载 Google Chrome Canary(版本 86),您将能够看到您的代码运行良好。Firefox 的版本为 78,并且自.replaceAll77 版开始可用,因此它也可以在该版本中使用。它也适用于当前的 Safari。Microsoft Edge 将其视为不受支持。

您会在问题中的文章底部找到支持的浏览器版本。


Pat*_*ari 17

如果您不想升级 Chrome 或使用 reg 表达式(因为它们的性能较低),您也可以这样做:

let string = ":insertx: :insertx: :inserty: :inserty: :insertz: :insertz:";
let newstring = string.split(":insertx:").join('hello!');
Run Code Online (Sandbox Code Playgroud)

当然,如果您想在任何地方都喜欢 String 原型,您也可以将其附加到 String 原型上。但由于真正的 replaceAll 功能更丰富(支持正则表达式),因此您可以更安全地执行以下操作:

String.prototype.replaceAllTxt = function replaceAll(search, replace) { return this.split(search).join(replace); }
Run Code Online (Sandbox Code Playgroud)

  • 惊人的。这应该是公认的答案,因为它还提供了解决方案,并且涵盖了兼容性问题。 (4认同)

小智 10

str.replaceAllES2021(ES12)中添加了该函数,这就是为什么它在旧版本的浏览器和nodejs中没有定义。


Ami*_*ati 7

你可以很容易地自己定义它:

if(typeof String.prototype.replaceAll == "undefined") {
    String.prototype.replaceAll = function(match, replace){
       return this.replace(new RegExp(match, 'g'), () => replace);
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

"fafa".replaceAll("a", "o");
>>> fofo
Run Code Online (Sandbox Code Playgroud)

  • p="fa.fa.fa".replaceAll(".", "o"); 控制台.log(p); // 呜呜呜 (2认同)