根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
当前回答
在与主要答案相关的性能方面,这些是某些在线测试。
虽然以下是使用 console.time() 的某些性能测试(它们在自己的控制台上工作最好,因为时间很短,可以在下面的剪辑中看到)。
值得注意的是,如果你运行它们多次,结果总是不同的,尽管正常的表达解决方案似乎是最快的平均,而旋转解决方案是最慢的。
其他回答
你可以尝试这样:
示例数据:
var text = "heloo,hai,hei"
text = text.replace(/[,]+/g, '')
或
text.forEach((value) => {
hasil = hasil.replace(',', '')
})
我的实践,非常自我解释
function replaceAll(string, token, newtoken) {
if(token!=newtoken)
while(string.indexOf(token) > -1) {
string = string.replace(token, newtoken);
}
return string;
}
在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代码的良好实践。
我只是想分享我的解决方案,基于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)
从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。
功能状态: https://chromestatus.com/feature/6040389083463680
var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)