根據一條線:

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”).加入(““)

其他回答

点击此处,我肯定会帮助你:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = 'Is this "3" dris "3"?';
  var allvar= '"3"';
  var patt1 = new RegExp( allvar, 'g' );
  document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>

这里是JSFiddle的链接。

最简单的解决方案 -

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”).加入(““)

把它推到发生的数字达到0,如下:

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

您可以使用下面的方法

/**
 * 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);
};

我建议通过将其附加到原型链上,为线类添加一个全球方法。

String.prototype.replaceAll = function(fromReplace, toReplace, {ignoreCasing} = {}) { return this.replace(new RegExp(fromReplace, ignoreCasing ? 'ig': 'g'), toReplace);}

它可以用作:

'stringwithpattern'.replaceAll('pattern', 'new-pattern')