根據一條線:
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', '');
如何替代所有事件?
当前回答
从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。
功能状态: https://chromestatus.com/feature/6040389083463680
var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)
其他回答
下面是基于接受答案的序列原型功能:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find, 'g'), replace);
};
如果你的发现包含特殊的字符,那么你需要逃避它们:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Fiddle: http://jsfiddle.net/cdbzL/
以前的答案太复杂了,只需使用替代功能如下:
str.replace(/your_regex_pattern/g, replacement_string);
例子:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);
使用分割并加入:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var replaced_str = str.split('abc').join(''); console.log(replaced_str);
虽然人们已经提到使用regex,如果你想取代文本的情况下,有一个更好的方法。
// Consider the below example
originalString.replace(/stringToBeReplaced/gi, '');
// The output will be all the occurrences removed irrespective of casing.
你可以在这里提到详细的例子。
String.prototype.replace 所有 - ECMAScript 2021
新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。
const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);