根據一條線:

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

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

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

如何替代所有事件?


当前回答

如果你想找到的东西已经在一条线上,你没有一个 regex escaper 方便,你可以使用 join/split:

函数替代Multi(haystack,针,替代) {返回 haystack.split(needle).join(替代); } someString = '猫看起来像猫'; console.log(替代Multi(someString, '猫', '狗'));

其他回答

在最受欢迎的浏览器的最新版本中,您可以使用 ReplaceAll 如下:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

但是,请检查我可以使用或其他兼容性表,首先确保您针对的浏览器首先添加了支持。


对于 Node.js 和旧/非当前浏览器的兼容性:

注意:不要在性能关键代码中使用下列解决方案。

作为一个简单的字体字符串的常规表达的替代品,您可以使用

str = "Test abc test test abc test...".split("abc").join("");

一般模式是

str.split(search).join(replacement)

这通常比在某些情况下更快,而不是使用替代所有和一个常见的表达式,但这似乎不再是现代浏览器的情况。

基准: https://jsben.ch/TZYzj

结论:

如果你有一个性能关键的使用案例(例如,处理数百条线),使用常规表达方法,但对于大多数典型的使用案例,这很好不需要担心特殊的字符。

您可以在没有Regex的情况下做到这一点,但如果替代文本包含搜索文本,则要小心。

吉。

replaceAll("nihIaohi", "hI", "hIcIaO", true)

因此,这里是一个合适的替代All 选项,包括字符串的原型:

function replaceAll(str, find, newToken, ignoreCase)
{
    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

    while ((
        i = (ignoreCase ? str.toLowerCase() : str).indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    } // Whend 

    return str;
}

或者,如果你想有一个字符串原型功能:

String.prototype.replaceAll = function (find, replace) {
    let str = this;

    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

    while ((
        i = (ignoreCase ? str.toLowerCase() : str).indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    } // Whend 

    return str;
};

说你想用“x”取代所有的“abc”:

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

我试图思考一些更简单的东西,而不是修改链条的原型。

使用常规表达式:

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

使用

str = str.replace(new RegExp("abc", 'g'), "");

因此,新的RegExp(“abc”,“g”)创造了一个常见的表达,符合所有事件(“g”旗帜)的文本(“abc”)。第二部分是什么被取代,在你的情况下,空线(“). str 是线,我们必须将它,作为替代(...)只是返回结果,但不超过。