根據一條線:

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

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

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

如何替代所有事件?


当前回答

这里是一个非常简单的解决方案. 您可以将一个新方法分配给一个 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 = "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"));

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>

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

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?]