根據一條線:

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

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

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

如何替代所有事件?


当前回答

替换单一引用:

function JavaScriptEncode(text){
    text = text.replace(/'/g,''')
    // More encode here if required

    return text;
}

其他回答

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

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

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

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

使用分割并加入:

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

试试这:

String.prototype.replaceAll = function (sfind, sreplace) {
    var str = this;

    while (str.indexOf(sfind) > -1) {
        str = str.replace(sfind, sreplace);
    }

    return str;
};

如果你试图确保你正在寻找的链条不会存在,即使在更换后,你需要使用一个旋转。

例如:

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

完成后,你将仍然有“测试ABC”!

最简单的路径来解决这个问题是:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

也许(在投票的危险下)可以结合为一个稍微更有效但更少可读的形式:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

例如,如果我们有“a、b”并希望删除所有复制曲线。 [在这种情况下,可以进行.replace(/+、/g、'),但在某个时候, regex 会变得复杂和缓慢,而不是旋转。