根據一條線:
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', '');
如何替代所有事件?
当前回答
str = "Test abc test test abc test test test abc test test abc"
str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')
其他回答
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);
HTTP://jsfiddle.net/ANHR9/
对抗全球常规表达:
anotherString = someString.replace(/cat/g, 'dog');
下面是基于接受答案的序列原型功能:
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/
截至 2020 年 8 月:现代浏览器支持由 ECMAScript 2021 语言规格定义的 String.replaceAll() 方法。
对于老/古老的浏览器:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
这就是这个答案的进化方式:
str = str.replace(/abc/g, '');
回复评论“如果“ABC”被转换为变量,会发生什么?”:
var find = 'abc';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
作为回应 Click Upvote 的评论,您可以更简化:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
注意: 常规表达式包含特殊(meta)字符,因此,它是危险的盲目通过一个论点在上面的查找函数,而不提前处理它逃避这些字符。
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
因此,为了使上面的替代All() 函数更安全,如果您还包含 EscapeRegExp:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
在与主要答案相关的性能方面,这些是某些在线测试。
虽然以下是使用 console.time() 的某些性能测试(它们在自己的控制台上工作最好,因为时间很短,可以在下面的剪辑中看到)。
值得注意的是,如果你运行它们多次,结果总是不同的,尽管正常的表达解决方案似乎是最快的平均,而旋转解决方案是最慢的。