根據一條線:

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

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

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

如何替代所有事件?


当前回答

您可以使用下面的方法

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};

其他回答

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;
}

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

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

例子:

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

首頁 〉外文書 〉文學 〉文學 〉In string first element search and replace

此分類上一篇: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員:

在线全球搜索和替换

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}' var j = str.replace(/\"\][g,'[').replace(/\]\"/g,']'); console.log(j,'//global search and replace')

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

或者尝试替代所有方法,如本答案所建议:

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

或:

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: 关于更换的澄清 所有可用性

替代All 方法将添加到 String 的原型,这意味着它将适用于所有 String 对象/字体。

例子:

var output = "test this".replaceAll('this', 'that'); // output is 'test that'.
output = output.replaceAll('that', 'this'); // output is 'test this'

以下功能为我工作:

String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

现在,请称这些功能如下:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

简单地复制并将此代码插入您的浏览器控制台进行测试。