根據一條線:
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(find, replace) {
var str = this;
return str.replace(new RegExp(find, 'g'), replace);
};
如果你的发现包含特殊的字符,那么你需要逃避它们:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Fiddle: http://jsfiddle.net/cdbzL/
其他回答
添加 /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 意味着全球性
表演
今天 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字符。
测试中使用的代码
在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代码的良好实践。
在最受欢迎的浏览器的最新版本中,您可以使用 ReplaceAll 如下:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
但是,请检查我可以使用或其他兼容性表,首先确保您针对的浏览器首先添加了支持。
对于 Node.js 和旧/非当前浏览器的兼容性:
注意:不要在性能关键代码中使用下列解决方案。
作为一个简单的字体字符串的常规表达的替代品,您可以使用
str = "Test abc test test abc test...".split("abc").join("");
一般模式是
str.split(search).join(replacement)
这通常比在某些情况下更快,而不是使用替代所有和一个常见的表达式,但这似乎不再是现代浏览器的情况。
基准: https://jsben.ch/TZYzj
结论:
如果你有一个性能关键的使用案例(例如,处理数百条线),使用常规表达方法,但对于大多数典型的使用案例,这很好不需要担心特殊的字符。
以下功能为我工作:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
现在,请称这些功能如下:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
简单地复制并将此代码插入您的浏览器控制台进行测试。