根據一條線:
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', '');
如何替代所有事件?
当前回答
重复,直到你已经取代了所有:
const regex = /^>.*/im;
while (regex.test(cadena)) {
cadena = cadena.replace(regex, '*');
}
其他回答
2020年8月
不再有常见的表达式
const str = “测试 abc 测试 abc 测试 abc 测试 abc”; const modifiedStr = str.replaceAll('abc', ''); console.log(modifiedStr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/Global_Objects/String/replaceAll
我在“图书馆”部分中添加了下面的功能到这个性能测试页面:
首頁 〉外文書 〉文學 〉文學 〉WEB
function _replace(t, s, r){
var i = t.indexOf(s);
if (i == -1) return t;
return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}
把它当作测试:
var replaced = _replace(testString, 'abc', '123');
想法的一部分是,如果链条不太大,它可能会在CPU存储库中结束;通过它并粘贴它的碎片将这些比特放入存储库中,然后搜索可以完全使用CPU存储数据运行。
这不是尽可能快的,但它是尽可能快的,我可以管理没有可转换的线条. 在JavaScript中的线条可能有一个指标每个元素,因此,一个解决方案涉及很多线条元素是不可能像CPU缓存友好。
我使用分割和加入或这个功能:
function replaceAll(text, busca, reemplaza) {
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca, reemplaza);
return text;
}
这里是一个非常简单的解决方案. 您可以将一个新方法分配给一个 String 对象
String.prototype.replaceAll = function(search, replace){
return this.replace(new RegExp(search, 'g'), replace)
}
var str = "Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');
console.log(str) // -> Test test test test test test test test
这是最常见、最可读的方法。
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