如何替换所有出现的字符串?

JavaScript

阿飞十三

2020-03-09

我有这个字符串:

"Test abc test test abc test test test abc test test abc"

正在做:

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

似乎只删除了abc上面字符串中的第一个匹配项

如何替换所有出现的内容?

第147篇《如何替换所有出现的字符串?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
西里米亚 2020.03.09

The previous answers are way too complicated. Just use the replace function like this:

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

Example:

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

var res = str.replace(/[abc]+/g, "");

console.log(res);

蛋蛋神乐 2020.03.09

If the string contain similar pattern like abccc, you can use this:

str.replace(/abc(\s|$)/g, "")
LEYTom 2020.03.09
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

路易Tom 2020.03.09

我喜欢这种方法(看起来更干净):

text = text.replace(new RegExp("cat","g"), "dog"); 
神奇阿良Jim 2020.03.09
function replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + replaceAll(st2, find, replace);
    }       
  }
  return str;
}
逆天西里 2020.03.09

//循环播放,直到出现的次数变为0。或者简单地复制/粘贴

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }
SamTony 2020.03.09

这是不使用正则表达式最快版本

修改过的jsperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

它的速度几乎是split and join方法的两倍

如此处的注释中所指出的,如果您的omit变量包含place,如:中的,这将不起作用replaceAll("string", "s", "ss"),因为它始终可以替换该单词的另一个出现。

我的递归替换中还有另一个jsperf,它的变体运行得更快(http://jsperf.com/replace-all-vs-split-join/12)!

  • 2017年7月27日更新:看起来RegExp现在在最近发布的Chrome 59中具有最快的性能。
番长GO 2020.03.09

使用正则表达式:

str.replace(/abc/g, '');
Harry神奇 2020.03.09

这些是最常见且易读的方法。

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 Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android