根據一條線:
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', '');
如何替代所有事件?
当前回答
把它推到发生的数字达到0,如下:
function replaceAll(find, replace, str) {
while (str.indexOf(find) > -1) {
str = str.replace(find, replace);
}
return str;
}
其他回答
我喜欢这个方法(看起来有点干净):
text = text.replace(new RegExp("cat","g"), "dog");
我使用p来存储以前的回归替换结果:
function replaceAll(s, m, r, p) {
return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}
它将取代链 s 的所有事件,直到它是可能的:
replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'
要避免无限旋转,我检查替代r是否包含一匹匹匹配m:
replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'
String.prototype.replace 所有 - ECMAScript 2021
新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。
const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);
这应该工作。
String.prototype.replaceAll = function (search, replacement) {
var str1 = this.replace(search, replacement);
var str2 = this;
while(str1 != str2) {
str2 = str1;
str1 = str1.replace(search, replacement);
}
return str1;
}
例子:
Console.log("Steve is the best character in Minecraft".replaceAll("Steve", "Alex"));
str = str.replace(/abc/g, '');
或者尝试替代所有方法,如本答案所建议:
str = str.replaceAll('abc', '');
或:
var search = 'abc';
str = str.replaceAll(search, '');
EDIT: 关于更换的澄清 所有可用性
替代All 方法将添加到 String 的原型,这意味着它将适用于所有 String 对象/字体。
例子:
var output = "test this".replaceAll('this', 'that'); // output is 'test that'.
output = output.replaceAll('that', 'this'); // output is 'test this'