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

I want to remove all 'user1,' from the string but by 'replace' method I can just remove one of them.

Sponge Bob
  • 377
  • 1
  • 5
  • 12

5 Answers5

2

try out this..

    var string = "user1,user2,user1,user3,user4,user1,";
    string.replace(/user1,/g, '');
    alert('string .. '+string);
Vijay
  • 8,131
  • 11
  • 43
  • 69
2

http://jsfiddle.net/79DgJ/

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

First parameter replace method can be regular expression. Use option 'g' for replace all matches.

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

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

Boris Kirov
  • 746
  • 7
  • 16
  • Thanks a lot. Now I want to use a variable instead of /user1,/ just like this: string.replace(/users+','/g, ''); – Sponge Bob Nov 27 '13 at 05:45
  • 1
    Use: `var number = 1, userRegExp = new RegExp('user' + number, 'g'); string = string.replace(userRegExp, '');` – Boris Kirov Nov 27 '13 at 05:52
2

use regexp

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

EDITED CODE

    var string = "user1,user2,user1,user3,user4,user1,";
    var find = 'user1';
    var re = new RegExp(find, 'g');
    string = string.replace(re, '');
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
2

try this, split the string, get the array, filter it to remove duplicate items, join them back.

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

Fiddle

Zeeshan
  • 1,659
  • 13
  • 17