根據一條線:

s = "Test abc test test abc test test test abc test test abc";

这似乎只是在上面的行中删除ABC的第一次出现:

s = s.replace('abc', '');

如何替代所有事件?


当前回答

有一个方法可以使用新的替代All() 方法。

但您需要使用先进的浏览器或JavaScript运行时间环境。

您可以在这里查看浏览器兼容性。

其他回答

虽然人们已经提到使用regex,如果你想取代文本的情况下,有一个更好的方法。

// Consider the below example
originalString.replace(/stringToBeReplaced/gi, '');

// The output will be all the occurrences removed irrespective of casing.

你可以在这里提到详细的例子。

这是最常见、最可读的方法。

var str = "Test abc test test abc test test test abc test test abc"

方法1:

str = str.replace(/abc/g, "replaced text");

方法2:

str = str.split("abc").join("replaced text");

方法3:

str = str.replace(new RegExp("abc", "g"), "replaced text");

方法4:

while(str.includes("abc")){
   str = str.replace("abc", "replaced text");
}

出口:

console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text

如果你想找到的东西已经在一条线上,你没有一个 regex escaper 方便,你可以使用 join/split:

函数替代Multi(haystack,针,替代) {返回 haystack.split(needle).join(替代); } someString = '猫看起来像猫'; console.log(替代Multi(someString, '猫', '狗'));

从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。

功能状态: https://chromestatus.com/feature/6040389083463680

var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)

以前的答案太复杂了,只需使用替代功能如下:

str.replace(/your_regex_pattern/g, replacement_string);

例子:

var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);