根據一條線:

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

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

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

如何替代所有事件?


当前回答

最简单的解决方案 -

let str = "Test abc test test abc test test test abc test test abc"; str = str.split(" "); str = str.filter((ele, key)=> ele!=="abc") str = str.join(" ")

或者只是 -

str = str.split(““)。过滤器(ele,键) => ele!=“abc”).加入(““)

其他回答

对抗全球常规表达:

anotherString = someString.replace(/cat/g, 'dog');

方法1

尝试执行一个常见的表达式:

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

方法2

与ABC分开并加入空空间。

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

截至 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);
}

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

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

要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。

替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。

replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。

const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));