根據一條線:

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

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

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

如何替代所有事件?


当前回答

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

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

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

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

其他回答

试试这:

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

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

    return str;
};

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

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 "

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

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

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

下面是实施细节:

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

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

下面是工作代码与原型:

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

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

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

要得到:

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