var string = "user1,user2,user1,user3,user4,user1,";
我想从字符串中删除所有'user1',但是'replace'方法我可以删除其中的一个。从字符串中删除两个相同的字符串
var string = "user1,user2,user1,user3,user4,user1,";
我想从字符串中删除所有'user1',但是'replace'方法我可以删除其中的一个。从字符串中删除两个相同的字符串
使用正则表达式
var string = "user1,user2,user1,user3,user4,user1,";
string.replace(/user1/g, '');
编辑的代码
var string = "user1,user2,user1,user3,user4,user1,";
var find = 'user1';
var re = new RegExp(find, 'g');
string = string.replace(re, '');
@SpongeBob勾选编辑的代码 –
听起来很好。对不起,我不能给你超过1分。 (这是我的答案。) –
var str= "user1,user2,user1,user3,user4,user1,";
str = str.replace(/user1,/g, ''); //replaces all 'user1,'
如何用/变量替换/ user1,/? –
第一个参数替换方法可以是正则表达式。 使用选项'g'替换所有匹配项。
var string = "user1,user2,user1,user3,user4,user1,";
string = string.replace(/user1,/g, '');
非常感谢。现在我想使用一个变量而不是/ user1,/就像这样:string.replace(/ users +','/ g,''); –
使用: '变种数= 1, userRegExp =新正则表达式( '用户' +号码, 'G'); 字符串=与string.replace(userRegExp, '');' – user3040347
试试这个, 分割字符串,得到的阵列,其过滤删除重复项,加入他们。
var uniqueList=string.split(',').filter(function(item,i,allItems){
return i==allItems.indexOf(item);
}).join(',');
嗯,这很好,但有点复杂。 –
请张贴你的代码。 –
重复的[JavaScript的.replace不全部替换](http://stackoverflow.com/q/12729449/218196)的 –
可能重复[使用Javascript多替换(http://stackoverflow.com/questions/832257/javascript-multiple-replace) –