根據一條線:

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

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

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

如何替代所有事件?


对抗全球常规表达:

anotherString = someString.replace(/cat/g, 'dog');

截至 2020 年 8 月:现代浏览器支持由 ECMAScript 2021 语言规格定义的 String.replaceAll() 方法。


对于老/古老的浏览器:

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

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

这就是这个答案的进化方式:

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

回复评论“如果“ABC”被转换为变量,会发生什么?”:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

作为回应 Click Upvote 的评论,您可以更简化:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}

注意: 常规表达式包含特殊(meta)字符,因此,它是危险的盲目通过一个论点在上面的查找函数,而不提前处理它逃避这些字符。

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

因此,为了使上面的替代All() 函数更安全,如果您还包含 EscapeRegExp:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), 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'

使用常规表达式:

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

在最受欢迎的浏览器的最新版本中,您可以使用 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

结论:

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

我的实践,非常自我解释

function replaceAll(string, token, newtoken) {
    if(token!=newtoken)
    while(string.indexOf(token) > -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

這是一個簡單的雷格斯,避免在大多數情況下取代字的部分. 然而,一個<unk> - 仍然被認為是字的邊界. 所以條件可以用在這種情況下,以避免取代線,如冷貓:

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

Regexp 不是唯一的替代多种现象的方法,远离它,思考灵活,思考分裂!

var newText = "the cat looks like a cat".split('cat').join('dog');

否则,要防止替代词部分 - 批准的答案也会做什么! 你可以通过常规的表达方式来围绕这个问题,我承认,有点复杂,并且作为一个惊喜,一个缓慢的,也:

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

结果与接受的答案相同,但是,在这个行上使用 /cat/g 表达式:

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

RegExp(常规表达式)对象 Regular-Expressions.info


在这种情况下,它显著简化表达,并提供更多的灵活性,如用正确的资本化替换或在一个行中替换两只猫和猫:

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       // Check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       { // Replace plurals, too
           cat = replacement + 's';
       }
       else
       { // Do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar

下面是基于接受答案的序列原型功能:

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

如果你的发现包含特殊的字符,那么你需要逃避它们:

String.prototype.replaceAll = function(find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};

Fiddle: http://jsfiddle.net/cdbzL/

我喜欢这个方法(看起来有点干净):

text = text.replace(new RegExp("cat","g"), "dog"); 

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

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

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

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


基于定期表达的实施

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 str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

HTTP://jsfiddle.net/ANHR9/

要取代所有类型的字符,请尝试此代码:

假设我们需要发送“和 \ 在我的行中,然后我们将转换“到“和 \ 到“。

因此,这种方法将解决这个问题。

String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
 };

var message = $('#message').val();
message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
message = message.replaceAll('"', '\\"');   /*it will replace " to \\"*/

我使用Ajax,我需要在JSON格式发送参数,然后我的方法看起来如下:

 function sendMessage(source, messageID, toProfileID, userProfileID) {

     if (validateTextBox()) {
         var message = $('#message').val();
         message = message.replaceAll('\\', '\\\\');
         message = message.replaceAll('"', '\\"');
         $.ajax({
             type: "POST",
             async: "false",
             contentType: "application/json; charset=utf-8",
             url: "services/WebService1.asmx/SendMessage",
             data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
             dataType: "json",
             success: function (data) {
                 loadMessageAfterSend(toProfileID, userProfileID);
                 $("#<%=PanelMessageDelete.ClientID%>").hide();
                 $("#message").val("");
                 $("#delMessageContainer").show();
                 $("#msgPanel").show();
             },
             error: function (result) {
                 alert("message sending failed");
             }
         });
     }
     else {
         alert("Please type message in message box.");
         $("#message").focus();

     }
 }

 String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
 };

试试这:

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

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

    return str;
};

这是最快的版本,不使用常规表达式。

修订 JSperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

它几乎比分裂和合并方法快两倍。

正如在评论中所指出的那样,如果你的错误变量包含位置,就不会工作,因为它总是能够取代另一个出现的词。

有另一个JSperf与我的回归替换的变量,它走得更快(http://jsperf.com/replace-all-vs-split-join/12)!

2017 年 7 月 27 日更新: 看起来 RegExp 现在在最近发布的 Chrome 59 中具有最快的性能。

while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。

// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;

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

例如:

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 会变得复杂和缓慢,而不是旋转。

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

添加 /g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

G 意味着全球性

替换单一引用:

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

    return text;
}

我使用p来存储以前的回归替换结果:

function replaceAll(s, m, r, p) {
    return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}

它将取代链 s 的所有事件,直到它是可能的:

replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'

要避免无限旋转,我检查替代r是否包含一匹匹匹配m:

replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'

您可以使用下面的方法

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

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

下面是工作代码与原型:

String.prototype.replaceAll = function(find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};
function replaceAll(str, find, replace) {
    var $r="";
    while($r!=str){ 
        $r = str;
        str = str.replace(find, replace);
    }
    return str;
}

虽然人们已经提到使用regex,如果你想取代文本的情况下,有一个更好的方法。

// Consider the below example
originalString.replace(/stringToBeReplaced/gi, '');

// The output will be all the occurrences removed irrespective of casing.

你可以在这里提到详细的例子。

说你想用“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

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

这可以用常规表达式和旗帜g来解决,这意味着在找到第一场比赛后不停止。

function replaceAll(string, pattern, replacement) {
    return string.replace(new RegExp(pattern, "g"), replacement);
}

// or if you want myString.replaceAll("abc", "");

String.prototype.replaceAll = function(pattern, replacement) {
    return this.replace(new RegExp(pattern, "g"), replacement);
};

要编码一个URL,你不应该只考虑空间,而是用编码URI正确地转换整个行。

encodeURI("http://www.google.com/a file with spaces.html")

要得到:

http://www.google.com/a%20file%20with%20spaces.html

在JavaScript中使用RegExp可以为您完成工作,只需在下面的代码中做一些类似的事情,不要忘记 /g 之后是全球性的:

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

如果你想重复使用,创建一个功能来为你做到这一点,但它不推荐,因为它只是一个线功能。

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

并简单地使用它在你的代码上和上如下:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

但是,正如我之前提到的那样,它不会在写字或性能方面产生巨大的差异. 只有加密功能可能会影响长线上的某些更快的性能,如果您想要重新使用,则是DRY代码的良好实践。

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

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;

如果链条包含类似的模式,如abccc,您可以使用以下模式:

str.replace(/abc(\s|$)/g, "")

首頁 〉外文書 〉文學 〉文學 〉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(new RegExp("abc", 'g'), "");

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

我只是想分享我的解决方案,基于JavaScript最新版本的一些功能功能:

   var str = "Test abc test test abc test test test abc test test abc";

   var result = str.split(' ').reduce((a, b) => {
      return b == 'abc' ? a : a + ' ' + b;   })

  console.warn(result)

可替代的独特价值

String.prototype.replaceAll = function(search_array, replacement_array) { // var target = this; // search_array.forEach(function(substr, index) { if (typeof replacement_array[index]!= "undefined") { target = target.replace(new RegExp(substr, 'g'), replacement_array[index] ) }); // return target; }; // Use: var replacedString = "This topic commented o

在与主要答案相关的性能方面,这些是某些在线测试。

虽然以下是使用 console.time() 的某些性能测试(它们在自己的控制台上工作最好,因为时间很短,可以在下面的剪辑中看到)。

值得注意的是,如果你运行它们多次,结果总是不同的,尽管正常的表达解决方案似乎是最快的平均,而旋转解决方案是最慢的。

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

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

例子:

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

你可以尝试这样:

示例数据:

var text = "heloo,hai,hei"

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

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

方法1

尝试执行一个常见的表达式:

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

方法2

与ABC分开并加入空空间。

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

最好的解决方案,以取代我们使用的任何字符的 indexOf(),包括(),和substring()功能,以取代相匹配的行与提供的行在当前行。

String.indexOf() 函数是找到 nth 匹配指数位置. String.includes() 方法确定一个行是否可以在另一个行中找到,随时返回真实或虚假。

下面的功能允许使用任何字符. 如 RegExp 不允许某些特殊字符如 ** 和某些字符需要逃避,如 $。

String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        //var matchArray = retStr.match(new RegExp(x, 'ig'));
        //for (var i = 0; i < matchArray.length; i++) {
        var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
        while (retStr.includes(x)) {
            retStr = retStr.replaceMatch(x, obj[x], 0);
            var replaceIndex = retStr.indexOf(x);
            if( replaceIndex <  prevIndex + (obj[x]).length) {
                break;
            } else {
                prevIndex = replaceIndex;
            }
        }
    }
    return retStr;
};
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    //var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
    //for (var x = 0; x < matchArray.length; x++) {
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

我们还可以使用常规表达式对象,以匹配文本与模式,以下是将常规表达式对象使用的功能。

String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
    }
    return retStr;
};

请注意,常规表达式是没有引用的。


var str = "yash yas $dfdas.**";
console.log('String: ', str);

// No need to escape any special character
console.log('Index matched replace: ', str.replaceMatch('as', '*', 2));
console.log('Index Matched replace: ', str.replaceMatch('y', '~', 1));
console.log('All Matched replace: ', str.replaceAllMatches({'as': '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**': '~~', '$':'&$&', '&':'%', '~':'>'}));

// You need to escape some special Characters
console.log('REGEX all matched replace: ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));

结果:

String:  yash yas $dfdas.**
Index Matched replace:  yash yas $dfd*.**
Index Matched replace:  yash ~as $dfdas.**

All Matched replace:  Y**h Y** -dfd**.**
All Matched replace:  yash yas %$%dfdas.>>

REGEX All Matched replace:  Y**h Y** -dfd**.**

最简单的解决方案 -

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

可以用常见的表达方式实现这一点,有几种可以帮助某人:

var word = "this,\\ .is*a*test,    '.and? / only /     'a \ test?";
var stri = "This      is    a test         and only a        test";

取代所有非阿尔法字符,

console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' '));
Result: [this is a test and only a test]

用一个空间替换多个连续空间,

console.log(stri.replace(/  +/g,' '));
Result: [This is a test and only a test]

取代所有 * 字符,

console.log(word.replace(/\*/g,''));
Result: [this,\ .isatest,    '.and? / only /     'a  test?]

取代问题标志(?)

console.log(word.replace(/\?/g,'#'));
Result: [this,\ .is*a*test,    '.and# / only /     'a  test#]

取代引用标志,

console.log(word.replace(/'/g,'#'));
Result: [this,\ .is*a*test,    #.and? / only /     #a  test?]

要取代所有“字符”,

console.log(word.replace(/,/g,''));
Result: [this\ .is*a*test    '.and? / only /     'a  test?]

替换一个特定的词,

console.log(word.replace(/test/g,''));
Result: [this,\ .is*a*,    '.and? / only /     'a  ?]

取代Backslash。

console.log(word.replace(/\\/g,''));
Result: [this, .is*a*test,    '.and? / only /     'a  test?]

以替代前滑,

console.log(word.replace(/\//g,''));
Result: [this,\ .is*a*test,    '.and?  only      'a  test?]

替换所有空间,

console.log(word.replace(/ /g,'#'));
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]

替换点,

console.log(word.replace(/\./g,'#'));
Result: [this,\ #is*a*test,    '#and? / only /     'a  test?]
var myName = 'r//i//n//o//l////d';
var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold
console.log(myValidName);

var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog

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

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

我使用分割和加入或这个功能:

function replaceAll(text, busca, reemplaza) {
  while (text.toString().indexOf(busca) != -1)
    text = text.toString().replace(busca, reemplaza);
  return text;
}

这应该工作。

String.prototype.replaceAll = function (search, replacement) {
    var str1 = this.replace(search, replacement);
    var str2 = this;
    while(str1 != str2) {
        str2 = str1;
        str1 = str1.replace(search, replacement);
    }
    return str1;
}

例子:

Console.log("Steve is the best character in Minecraft".replaceAll("Steve", "Alex"));

最简单的方式来做到这一点,而不使用任何常规表达式是分裂并加入,如这里的代码:

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

所有答案都被接受,你可以以多种方式做到这一点。

const str = “测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试

要替换一次,使用:

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

多次替换,使用:

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

看看这个答案,也许它会帮助,我在我的项目中使用它。

function replaceAll(searchString, replaceString, str) {
    return str.split(searchString).join(replaceString);
}

replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "

您可以在没有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;
};
str = "Test abc test test abc test test test abc test test abc"

str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')

现在有一个完整的建议,将 String.prototype.replaceAll 集成到官方规格中. 最终,开发人员将不需要自己的实施来取代All - 相反,现代的 JavaScript 引擎将以原始方式支持它。

提议是在4阶段,这意味着一切都完成了,剩下的就是浏览器开始实施它。

它已经发送在最新版本的Chrome,Firefox,和Safari。

下面是实施细节:

根据当前的 TC39 共识, String.prototype.replace 所有行为相同于 String.prototype.replace 在所有情况下,除了下列两种情况: 如果 searchValue 是一个行, String.prototype.replace 只取代一个单一的事件的事件的事件的事件的事件,而 String.prototype.replace 所有事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件的事件。

你可以在这里看到一个符合规格的聚合物。

截至2020年8月,为ECMAScript提供了一个阶段4的提议,该提议将替代All 方法添加到 String。

它现在支持Chrome 85+,Edge 85+,Firefox 77+,Safari 13.1+。

使用方式与替代方法相同:

String.prototype.replaceAll(searchValue, replaceValue)

下面是使用例子:

'Test abc test test abc test.'.replaceAll('abc', 'foo'); // -> 'Test foo test test foo test.'

它在大多数现代浏览器中支持,但有多元化:

核心JS Es-Shims

它支持在V8发动机背后一个实验旗帜 - 和谐 - 带 - 替代。

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

<!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的链接。

2019年11月,新功能被添加到JavaScript, string.prototype.replaceAll()。

目前它仅支持巴比伦,但也许在未来它可以在所有浏览器中实施。

表演

今天 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字符。

测试中使用的代码

我们可以在JavaScript中使用替代方法:

var result = yourString.replace('regexPattern', "replaceString");

var str = “测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试

我知道这不是最好的办法,但你可以尝试一下:

var annoyingString = "Test abc test test abc test test test abc test test abc";

while (annoyingString.includes("abc")) {
    annoyingString = annoyingString.replace("abc", "")
}

我在“图书馆”部分中添加了下面的功能到这个性能测试页面:

首頁 〉外文書 〉文學 〉文學 〉WEB

function _replace(t, s, r){
    var i = t.indexOf(s);
    if (i == -1) return t;
    return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}

把它当作测试:

var replaced = _replace(testString, 'abc', '123');

想法的一部分是,如果链条不太大,它可能会在CPU存储库中结束;通过它并粘贴它的碎片将这些比特放入存储库中,然后搜索可以完全使用CPU存储数据运行。

这不是尽可能快的,但它是尽可能快的,我可以管理没有可转换的线条. 在JavaScript中的线条可能有一个指标每个元素,因此,一个解决方案涉及很多线条元素是不可能像CPU缓存友好。

从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。

功能状态: https://chromestatus.com/feature/6040389083463680

var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)

这里是一个非常简单的解决方案. 您可以将一个新方法分配给一个 String 对象

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

var str = "Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

console.log(str) // -> Test  test test  test test test  test test

使用分割并加入:

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

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

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

它可以用作:

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

2020年8月

不再有常见的表达式

const str = “测试 abc 测试 abc 测试 abc 测试 abc”; const modifiedStr = str.replaceAll('abc', ''); console.log(modifiedStr);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/Global_Objects/String/replaceAll

这个解决方案结合了一些以前的答案,并更好地符合建议的2020年8月标准解决方案,这个解决方案在2020年9月对我来说仍然可行,因为String.replaceAll不在我使用的Node.js二进制中。


RegExp.escape 是一个单独的问题处理,但它在这里很重要,因为官方提出的解决方案将自动逃脱基于链条的查找输入。


如果你需要准确的标准符合,对于一个应用程序,它是严格依赖于标准实施,那么我建议使用Babel或其他工具,你得到“正确的答案”每次而不是Stack Overflow。


代码:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(RegExp.escape(find), 'g'),
          replace
        );
  }
}

编码,小型:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});

例子:

console.log(
  't*.STVAL'
    .replaceAll(
      new RegExp(RegExp.escape('T*.ST'), 'ig'),
      'TEST'
    )
);

console.log(
  't*.STVAL'
    .replaceAll(
      't*.ST',
      'TEST'
    );
);

没有 RegExp.Escape 的代码:

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
          replace
        );
  }
}

代码没有 RegExp.Escape,小型:

Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});

有一个方法可以使用新的替代All() 方法。

但您需要使用先进的浏览器或JavaScript运行时间环境。

您可以在这里查看浏览器兼容性。

要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。

替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。

replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。

const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));

// Try this way

const str = "Test abc test test abc test test test abc test test abc";
const result = str.split('abc').join('');
console.log(result);

与常规表达的i旗案例不敏感

console.log('App started'.replace(/a/g, '')) // Result: "App strted"
console.log('App started'.replace(/a/gi, '')) // Result: "pp strted"

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

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

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

重复,直到你已经取代了所有:

const regex = /^>.*/im;
while (regex.test(cadena)) {
    cadena = cadena.replace(regex, '*');
}

String.prototype.replace 所有 - ECMAScript 2021

新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。

const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);

我已经阅读了这个问题和答案,但我找不到一个合适的解决方案,虽然答案是相当有用的,我决定创建自己的解决方案从切割。

例如,对于搜索结果,我需要用相同的案例取代它,如果我处理内部HTML,我可以轻松地损害HTML标签(例如,在href属性中出现 hr)。

因此,我写的功能,以突出搜索结果在一个表,在那里表数据细胞可能有链接在内部,以及其他HTML标签。

我決定為所有人提供相同的問題的解決方案. 當然,你可以用它不僅為表,但為任何元素。

/* Iterate over table data cells to insert a highlight tag */
function highlightSearchResults(textFilter) {
  textFilter = textFilter.toLowerCase().replace('<', '&lt;').replace('>', '&gt;');
  let tds;
  tb = document.getElementById('sometable'); //root element where to search
  if (tb) {
    tds = tb.getElementsByTagName("td"); //sub-elements where to make replacements
  }
  if (textFilter && tds) {
    for (td of tds) {
      //specify your span class or whatever you need before and after
      td.innerHTML = insertCaseInsensitive(td.innerHTML, textFilter, '<span class="highlight">', '</span>');
    }
  }
}

/* Insert a highlight tag */
function insertCaseInsensitive(srcStr, lowerCaseFilter, before, after) {
  let lowStr = srcStr.toLowerCase();
  let flen = lowerCaseFilter.length;
  let i = -1;
  while ((i = lowStr.indexOf(lowerCaseFilter, i + 1)) != -1) {
    if (insideTag(i, srcStr)) continue;
    srcStr = srcStr.slice(0, i) + before + srcStr.slice(i, i+flen) + after + srcStr.slice(i+flen);
    lowStr = srcStr.toLowerCase();
    i += before.length + after.length;
  }
  return srcStr;
}

/* Check if an ocurrence is inside any tag by index */
function insideTag(si, s) {
  let ahead = false;
  let back = false;
  for (let i = si; i < s.length; i++) {
    if (s[i] == "<") {
      break;
    }
    if (s[i] == ">") {
      ahead = true;
      break;
    }
  }
  for (let i = si; i >= 0; i--) {
    if (s[i] == ">") {
      break;
    }
    if (s[i] == "<") {
      back = true;
      break;
    }
  }
  return (ahead && back);
}

String.prototype.replace 所有()

如果你不想处理替代() + RegExp。

但是,如果浏览器在2020年之前?

我推荐的替代All polyfill的选项:

替代All polyfill (与全球旗帜错误) (更多原则版)

if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}

替代All polyfill (With handling global-flag missing by itself) (我的第一个偏好) - 为什么?

if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}

小型(我的第一个偏好):

if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}


其他方法的聚合物分配

if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function(search, replace) { // <-- Naive method for assignment
        // ... (Polyfill code Here)
    }
}

for (var k in 'hi') console.log(k);
// 0
// 1
// replaceAll  <-- ?

非常可靠,但重

事实上,我提出的选项有点乐观,正如我们信任环境(浏览器和Node.js),它肯定是2012年至2021年左右。

此分類上一篇: HTTPS://polyfill.io

特别是替代:

<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>