根據一條線:
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', '');
如何替代所有事件?
当前回答
我只是想分享我的解决方案,基于JavaScript最新版本的一些功能功能:
var str = "Test abc test test abc test test test abc test test abc";
var result = str.split(' ').reduce((a, b) => {
return b == 'abc' ? a : a + ' ' + b; })
console.warn(result)
其他回答
以前的答案太复杂了,只需使用替代功能如下:
str.replace(/your_regex_pattern/g, replacement_string);
例子:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);
对抗全球常规表达:
anotherString = someString.replace(/cat/g, 'dog');
以下功能为我工作:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
现在,请称这些功能如下:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
简单地复制并将此代码插入您的浏览器控制台进行测试。
使用常规表达式:
str.replace(/abc/g, '');
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}