根據一條線:
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', '');
如何替代所有事件?
当前回答
就像上面的分裂/合并解决方案一样,下面的解决方案与逃避字符没有任何问题,与常规表达方法不同。
function replaceAll(s, find, repl, caseOff, byChar) {
if (arguments.length<2)
return false;
var destDel = ! repl; // If destDel delete all keys from target
var isString = !! byChar; // If byChar, replace set of characters
if (typeof find !== typeof repl && ! destDel)
return false;
if (isString && (typeof find !== "string"))
return false;
if (! isString && (typeof find === "string")) {
return s.split(find).join(destDel ? "" : repl);
}
if ((! isString) && (! Array.isArray(find) ||
(! Array.isArray(repl) && ! destDel)))
return false;
// If destOne replace all strings/characters by just one element
var destOne = destDel ? false : (repl.length === 1);
// Generally source and destination should have the same size
if (! destOne && ! destDel && find.length !== repl.length)
return false
var prox, sUp, findUp, i, done;
if (caseOff) { // Case insensitive
// Working with uppercase keys and target
sUp = s.toUpperCase();
if (isString)
findUp = find.toUpperCase()
else
findUp = find.map(function(el) {
return el.toUpperCase();
});
}
else { // Case sensitive
sUp = s;
findUp = find.slice(); // Clone array/string
}
done = new Array(find.length); // Size: number of keys
done.fill(null);
var pos = 0; // Initial position in target s
var r = ""; // Initial result
var aux, winner;
while (pos < s.length) { // Scanning the target
prox = Number.MAX_SAFE_INTEGER;
winner = -1; // No winner at the start
for (i=0; i<findUp.length; i++) // Find next occurence for each string
if (done[i]!==-1) { // Key still alive
// Never search for the word/char or is over?
if (done[i] === null || done[i] < pos) {
aux = sUp.indexOf(findUp[i], pos);
done[i] = aux; // Save the next occurrence
}
else
aux = done[i] // Restore the position of last search
if (aux < prox && aux !== -1) { // If next occurrence is minimum
winner = i; // Save it
prox = aux;
}
} // Not done
if (winner === -1) { // No matches forward
r += s.slice(pos);
break;
} // No winner
// Found the character or string key in the target
i = winner; // Restore the winner
r += s.slice(pos, prox); // Update piece before the match
// Append the replacement in target
if (! destDel)
r += repl[destOne ? 0 : i];
pos = prox + (isString ? 1 : findUp[i].length); // Go after match
} // Loop
return r; // Return the resulting string
}
文档如下:
替代All Syntax ====== 替代All(s, find, [repl, caseOff, byChar) 参数 ==========“s” 是替代序列的目标. “find” 可以是序列或序列的序列. “repl” 应该是相同的类型“find” 或空的 如果“find” 是序列,它是一个简单的替代所有“find” 事件在“s” 由序列“repl” 如果“find” 是序列,它将取代
function l() {
return console.log.apply(null, arguments);
}
var k = 0;
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do", "fa"])); // 1
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do"])); // 2
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"])); // 3
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "", "", true)); // 4
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "a", "", true)); // 5
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "uoiea", "", true)); // 6
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "uoi", "", true)); // 7
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do", "fa", "leg"])); // 8
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri", "nea"], ["do", "fa"])); // 9
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri", "nea"], ["do", "fa"], true)); // 10
return;
其他回答
表演
今天 2019 年 12 月 27 日 我在 macOS v10.13.6 (High Sierra) 上进行测试,以便选择的解决方案。
结论
基于分合(A、B)或替换(C、D)的解决方案是基于时间的快速解决方案(E、F、G、H)是缓慢的 - 通常是小线的4倍缓慢,长线的约3000倍缓慢。
str.split`abc`.join``
细节
此分類上一篇
短字 - 55 个字符
您可以在您的机器上运行测试 此处. Chrome 的结果:
此分類上一篇
重复解决方案 RA 和 RB 提供
对于1M字符,他们甚至打破了Chrome
此分類上一篇
我试图为其他解决方案进行1M字符的测试,但E、F、G、H需要这么长时间,浏览器要求我打破脚本,所以我将测试行缩短到275K字符。
测试中使用的代码
点击此处,我肯定会帮助你:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = 'Is this "3" dris "3"?';
var allvar= '"3"';
var patt1 = new RegExp( allvar, 'g' );
document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>
这里是JSFiddle的链接。
String.prototype.replace 所有 - ECMAScript 2021
新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。
const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);
有一个方法可以使用新的替代All() 方法。
但您需要使用先进的浏览器或JavaScript运行时间环境。
您可以在这里查看浏览器兼容性。
最简单的解决方案 -
let str = "Test abc test test abc test test test abc test test abc"; str = str.split(" "); str = str.filter((ele, key)=> ele!=="abc") str = str.join(" ")
或者只是 -
str = str.split(““)。过滤器(ele,键) => ele!=“abc”).加入(““)