根據一條線:

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

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

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

如何替代所有事件?


当前回答

使用分割并加入:

var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var replaced_str = str.split('abc').join(''); console.log(replaced_str);

其他回答

我知道这不是最好的办法,但你可以尝试一下:

var annoyingString = "Test abc test test abc test test test abc test test abc";

while (annoyingString.includes("abc")) {
    annoyingString = annoyingString.replace("abc", "")
}

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

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

经过几次尝试和很多失败,我发现下面的功能似乎是最好的全环,当涉及到浏览器兼容性和易于使用时,这是我发现的旧浏览器的唯一工作解决方案。

无论如何,这里是简单的功能。

function replaceAll(str, match, replacement){
   return str.split(match).join(replacement);
}

截至 2020 年 8 月:现代浏览器支持由 ECMAScript 2021 语言规格定义的 String.replaceAll() 方法。


对于老/古老的浏览器:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

这就是这个答案的进化方式:

str = str.replace(/abc/g, '');

回复评论“如果“ABC”被转换为变量,会发生什么?”:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

作为回应 Click Upvote 的评论,您可以更简化:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}

注意: 常规表达式包含特殊(meta)字符,因此,它是危险的盲目通过一个论点在上面的查找函数,而不提前处理它逃避这些字符。

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

因此,为了使上面的替代All() 函数更安全,如果您还包含 EscapeRegExp:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

要编码一个URL,你不应该只考虑空间,而是用编码URI正确地转换整个行。

encodeURI("http://www.google.com/a file with spaces.html")

要得到:

http://www.google.com/a%20file%20with%20spaces.html