2013-11-27 140 views
1
var string = "user1,user2,user1,user3,user4,user1,"; 

我想从字符串中删除所有'user1',但是'replace'方法我可以删除其中的一个。从字符串中删除两个相同的字符串

+0

请张贴你的代码。 –

+0

重复的[JavaScript的.replace不全部替换](http://stackoverflow.com/q/12729449/218196)的 –

+0

可能重复[使用Javascript多替换(http://stackoverflow.com/questions/832257/javascript-multiple-replace) –

回答

2

使用正则表达式

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, ''); 
+0

@SpongeBob勾选编辑的代码 –

+0

听起来很好。对不起,我不能给你超过1分。 (这是我的答案。) –

2

试试这个..

var string = "user1,user2,user1,user3,user4,user1,"; 
    string.replace(/user1,/g, ''); 
    alert('string .. '+string); 
+0

'replaceAll'是jquery的! – rps

+0

JavaScript库中似乎没有'replaceAll'方法。我如何使用它? –

+0

'@Sponge Bob'请找到已编辑的答案... – Vijay

2

http://jsfiddle.net/79DgJ/

var str= "user1,user2,user1,user3,user4,user1,"; 
str = str.replace(/user1,/g, ''); //replaces all 'user1,' 
+0

如何用/变量替换/ user1,/? –

2

第一个参数替换方法可以是正则表达式。 使用选项'g'替换所有匹配项。

var string = "user1,user2,user1,user3,user4,user1,";

string = string.replace(/user1,/g, '');

+0

非常感谢。现在我想使用一个变量而不是/ user1,/就像这样:string.replace(/ users +','/ g,''); –

+1

使用: '变种数= 1, userRegExp =新正则表达式( '用户' +号码, 'G'); 字符串=与string.replace(userRegExp, '');' – user3040347

2

试试这个, 分割字符串,得到的阵列,其过滤删除重复项,加入他们。

var uniqueList=string.split(',').filter(function(item,i,allItems){ 
    return i==allItems.indexOf(item); 
}).join(','); 

Fiddle

+0

嗯,这很好,但有点复杂。 –