根據一條線:
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', '');
如何替代所有事件?
当前回答
这是最常见、最可读的方法。
var str = "Test abc test test abc test test test abc test test abc"
方法1:
str = str.replace(/abc/g, "replaced text");
方法2:
str = str.split("abc").join("replaced text");
方法3:
str = str.replace(new RegExp("abc", "g"), "replaced text");
方法4:
while(str.includes("abc")){
str = str.replace("abc", "replaced text");
}
出口:
console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text
其他回答
在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代码的良好实践。
我喜欢这个方法(看起来有点干净):
text = text.replace(new RegExp("cat","g"), "dog");
对抗全球常规表达:
anotherString = someString.replace(/cat/g, 'dog');
经过几次尝试和很多失败,我发现下面的功能似乎是最好的全环,当涉及到浏览器兼容性和易于使用时,这是我发现的旧浏览器的唯一工作解决方案。
无论如何,这里是简单的功能。
function replaceAll(str, match, replacement){
return str.split(match).join(replacement);
}
下面是工作代码与原型:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};