根據一條線:
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', '');
如何替代所有事件?
当前回答
您可以使用下面的方法
/**
* Replace all the occerencess of $find by $replace in $originalString
* @param {originalString} input - Raw string.
* @param {find} input - Target key word or regex that need to be replaced.
* @param {replace} input - Replacement key word
* @return {String} Output string
*/
function replaceAll(originalString, find, replace) {
return originalString.replace(new RegExp(find, 'g'), replace);
};
其他回答
以前的答案太复杂了,只需使用替代功能如下:
str.replace(/your_regex_pattern/g, replacement_string);
例子:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);
要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。
替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。
replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。
const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));
使用分割并加入:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var replaced_str = str.split('abc').join(''); console.log(replaced_str);
从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。
功能状态: https://chromestatus.com/feature/6040389083463680
var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)
使用常规表达式:
str.replace(/abc/g, '');