根據一條線:
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 text = "heloo,hai,hei"
text = text.replace(/[,]+/g, '')
或
text.forEach((value) => {
hasil = hasil.replace(',', '')
})
其他回答
在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代码的良好实践。
我使用分割和加入或这个功能:
function replaceAll(text, busca, reemplaza) {
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca, reemplaza);
return text;
}
看看这个答案,也许它会帮助,我在我的项目中使用它。
function replaceAll(searchString, replaceString, str) {
return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test test test test test test test test "
在最受欢迎的浏览器的最新版本中,您可以使用 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
结论:
如果你有一个性能关键的使用案例(例如,处理数百条线),使用常规表达方法,但对于大多数典型的使用案例,这很好不需要担心特殊的字符。
// Try this way
const str = "Test abc test test abc test test test abc test test abc";
const result = str.split('abc').join('');
console.log(result);