0

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.

1
  • I was able to remove the duplicates at the end of the String using the follwoing expression.str = str.replace(/,+$/, ","); How do i do it in the middle of the String? Commented Nov 28, 2013 at 10:43

4 Answers 4

1

Try this:

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

http://jsfiddle.net/bnQt4/

Sign up to request clarification or add additional context in comments.

2 Comments

I have a doubt.what does {2,} do in the above expression?
@sathishkumar it means match it 2 or more times
0

How about:

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.