根據一條線:

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

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

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

如何替代所有事件?


当前回答

就像上面的分裂/合并解决方案一样,下面的解决方案与逃避字符没有任何问题,与常规表达方法不同。

function replaceAll(s, find, repl, caseOff, byChar) {
    if (arguments.length<2)
        return false;
    var destDel = ! repl;       // If destDel delete all keys from target
    var isString = !! byChar;   // If byChar, replace set of characters
    if (typeof find !== typeof repl && ! destDel)
        return false;
    if (isString && (typeof find !== "string"))
        return false;

    if (! isString && (typeof find === "string")) {
        return s.split(find).join(destDel ? "" : repl);
    }

    if ((! isString) && (! Array.isArray(find) ||
        (! Array.isArray(repl) && ! destDel)))
        return false;

    // If destOne replace all strings/characters by just one element
    var destOne = destDel ? false : (repl.length === 1);

    // Generally source and destination should have the same size
    if (! destOne && ! destDel && find.length !== repl.length)
        return false

    var prox, sUp, findUp, i, done;
    if (caseOff)  { // Case insensitive

    // Working with uppercase keys and target
    sUp = s.toUpperCase();
    if (isString)
       findUp = find.toUpperCase()
    else
       findUp = find.map(function(el) {
                    return el.toUpperCase();
                });
    }
    else { // Case sensitive
        sUp = s;
        findUp = find.slice(); // Clone array/string
    }

    done = new Array(find.length); // Size: number of keys
    done.fill(null);

    var pos = 0;  // Initial position in target s
    var r = "";   // Initial result
    var aux, winner;
    while (pos < s.length) {       // Scanning the target
        prox  = Number.MAX_SAFE_INTEGER;
        winner = -1;  // No winner at the start
        for (i=0; i<findUp.length; i++) // Find next occurence for each string
            if (done[i]!==-1) { // Key still alive

                // Never search for the word/char or is over?
                if (done[i] === null || done[i] < pos) {
                    aux = sUp.indexOf(findUp[i], pos);
                    done[i] = aux;  // Save the next occurrence
                }
                else
                    aux = done[i]   // Restore the position of last search

                if (aux < prox && aux !== -1) { // If next occurrence is minimum
                    winner = i; // Save it
                    prox = aux;
                }
        } // Not done

        if (winner === -1) { // No matches forward
            r += s.slice(pos);
            break;
        } // No winner

        // Found the character or string key in the target

        i = winner;  // Restore the winner
        r += s.slice(pos, prox); // Update piece before the match

        // Append the replacement in target
        if (! destDel)
            r += repl[destOne ? 0 : i];
        pos = prox + (isString ? 1 : findUp[i].length); // Go after match
    }  // Loop

    return r; // Return the resulting string
}

文档如下:

替代All Syntax ====== 替代All(s, find, [repl, caseOff, byChar) 参数 ==========“s” 是替代序列的目标. “find” 可以是序列或序列的序列. “repl” 应该是相同的类型“find” 或空的 如果“find” 是序列,它是一个简单的替代所有“find” 事件在“s” 由序列“repl” 如果“find” 是序列,它将取代

function l() {
    return console.log.apply(null, arguments);
}

var k = 0;
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      ["ri", "nea"], ["do", "fa"]));  // 1
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      ["ri", "nea"], ["do"])); // 2
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      ["ri", "nea"])); // 3
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
     "aeiou", "", "", true)); // 4
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou", "a", "", true)); // 5
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou", "uoiea", "", true)); // 6
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou", "uoi", "", true)); // 7
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
      ["ri", "nea"], ["do", "fa", "leg"])); // 8
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri", "nea"], ["do", "fa"])); // 9
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri", "nea"], ["do", "fa"], true)); // 10
return;

其他回答

经过几次尝试和很多失败,我发现下面的功能似乎是最好的全环,当涉及到浏览器兼容性和易于使用时,这是我发现的旧浏览器的唯一工作解决方案。

无论如何,这里是简单的功能。

function replaceAll(str, match, replacement){
   return str.split(match).join(replacement);
}


基于定期表达的实施

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

看看这个参数运行这两个实施对彼此。


正如 @ThomasLeduc 和其他人在下面的评论中所指出的那样,如果搜索包含某些字符,这些字符在常规表达式中被保留为特殊字符,则可能会出现常规表达式的实施问题。

MDN 还提供了一个实施,以逃避我们的线条. 如果它也被标准化为 RegExp.escape(str),但不幸的是,它不存在:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

你可以尝试这样:

示例数据:

var text = "heloo,hai,hei"

text = text.replace(/[,]+/g, '')

text.forEach((value) => {
  hasil = hasil.replace(',', '')
})

要替换一次,使用:

var res = str.replace('abc', "");

多次替换,使用:

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

表演

今天 2019 年 12 月 27 日 我在 macOS v10.13.6 (High Sierra) 上进行测试,以便选择的解决方案。

结论

基于分合(A、B)或替换(C、D)的解决方案是基于时间的快速解决方案(E、F、G、H)是缓慢的 - 通常是小线的4倍缓慢,长线的约3000倍缓慢。

str.split`abc`.join``

细节

此分類上一篇

短字 - 55 个字符

您可以在您的机器上运行测试 此处. Chrome 的结果:

此分類上一篇

重复解决方案 RA 和 RB 提供

对于1M字符,他们甚至打破了Chrome

此分類上一篇

我试图为其他解决方案进行1M字符的测试,但E、F、G、H需要这么长时间,浏览器要求我打破脚本,所以我将测试行缩短到275K字符。

测试中使用的代码