sathish kumar
sathish kumar

Reputation: 1197

removing duplicates in a string using javascript

I have a string like the one given below.

String1 = "a,b,,,c"

I want to replace the commas occuring in the middle with a single comma i.e. remove duplicate values.How would I do it.

Upvotes: 0

Views: 92

Answers (4)

Firas Dib
Firas Dib

Reputation: 2621

Here is something fairly generic that would work for any repeated string: /(.)(?=\1)/g

If you only want commas, simply use /,(?=,)/g

Replace the result with an empty string.

string1 = string1.replace(/,(?=,)/g, '');

Demo: http://regex101.com/r/zA0kQ4

Upvotes: 0

anubhava
anubhava

Reputation: 785156

This should work:

string1="a,b,,,c";
repl = string1.replace(/,{2}/g, '');
//=> a,b,c

OR using lookahead:

repl = string1.replace(/,(?=,)/g, '');
//=> a,b,c

Upvotes: 0

Toto
Toto

Reputation: 91415

How about:

String1.replace(/,+/g, ',');

Upvotes: 0

Andrew
Andrew

Reputation: 5340

Try this:

str.replace(/[,]{2,}/g, ',')

http://jsfiddle.net/bnQt4/

Upvotes: 1

Related Questions