根據一條線:
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', '');
如何替代所有事件?
当前回答
我建议通过将其附加到原型链上,为线类添加一个全球方法。
String.prototype.replaceAll = function(fromReplace, toReplace, {ignoreCasing} = {}) { return this.replace(new RegExp(fromReplace, ignoreCasing ? 'ig': 'g'), toReplace);}
它可以用作:
'stringwithpattern'.replaceAll('pattern', 'new-pattern')
其他回答
最简单的方式来做到这一点,而不使用任何常规表达式是分裂并加入,如这里的代码:
var str = “测试 abc 测试 abc 测试 abc 测试 abc 测试 abc”; console.log(str.split('abc').join(''));
在与主要答案相关的性能方面,这些是某些在线测试。
虽然以下是使用 console.time() 的某些性能测试(它们在自己的控制台上工作最好,因为时间很短,可以在下面的剪辑中看到)。
值得注意的是,如果你运行它们多次,结果总是不同的,尽管正常的表达解决方案似乎是最快的平均,而旋转解决方案是最慢的。
如果链条包含类似的模式,如abccc,您可以使用以下模式:
str.replace(/abc(\s|$)/g, "")
可替代的独特价值
String.prototype.replaceAll = function(search_array, replacement_array) { // var target = this; // search_array.forEach(function(substr, index) { if (typeof replacement_array[index]!= "undefined") { target = target.replace(new RegExp(substr, 'g'), replacement_array[index] ) }); // return target; }; // Use: var replacedString = "This topic commented o
对抗全球常规表达:
anotherString = someString.replace(/cat/g, 'dog');