根據一條線:
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', '');
如何替代所有事件?
当前回答
有一个方法可以使用新的替代All() 方法。
但您需要使用先进的浏览器或JavaScript运行时间环境。
您可以在这里查看浏览器兼容性。
其他回答
要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。
替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。
replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。
const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));
我只是想分享我的解决方案,基于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)
如果你试图确保你正在寻找的链条不会存在,即使在更换后,你需要使用一个旋转。
例如:
var str = 'test aabcbc';
str = str.replace(/abc/g, '');
完成后,你将仍然有“测试ABC”!
最简单的路径来解决这个问题是:
var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
str.replace(/abc/g, '');
}
也许(在投票的危险下)可以结合为一个稍微更有效但更少可读的形式:
var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!
例如,如果我们有“a、b”并希望删除所有复制曲线。 [在这种情况下,可以进行.replace(/+、/g、'),但在某个时候, regex 会变得复杂和缓慢,而不是旋转。
表演
今天 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字符。
测试中使用的代码
如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;