根據一條線:

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

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

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

如何替代所有事件?


当前回答

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

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

其他回答

我的实践,非常自我解释

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

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

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

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

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

添加 /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 意味着全球性

使用

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

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

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

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

要得到:

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