根據一條線:
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', '');
如何替代所有事件?
当前回答
如果你想找到的东西已经在一条线上,你没有一个 regex escaper 方便,你可以使用 join/split:
函数替代Multi(haystack,针,替代) {返回 haystack.split(needle).join(替代); } someString = '猫看起来像猫'; console.log(替代Multi(someString, '猫', '狗'));
其他回答
我的实践,非常自我解释
function replaceAll(string, token, newtoken) {
if(token!=newtoken)
while(string.indexOf(token) > -1) {
string = string.replace(token, newtoken);
}
return string;
}
function replaceAll(str, find, replace) {
var $r="";
while($r!=str){
$r = str;
str = str.replace(find, replace);
}
return str;
}
对抗全球常规表达:
anotherString = someString.replace(/cat/g, 'dog');
表演
今天 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字符。
测试中使用的代码
我知道这不是最好的办法,但你可以尝试一下:
var annoyingString = "Test abc test test abc test test test abc test test abc";
while (annoyingString.includes("abc")) {
annoyingString = annoyingString.replace("abc", "")
}