Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have found a way to remove repeated characters from a string using regular expressions.

function RemoveDuplicates() {
    var str = "aaabbbccc";
    var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");  
    alert(filtered);
}

Output: abc this is working fine.

But if str = "aaabbbccccabbbbcccccc" then output is abcabc. Is there any way to get only unique characters or remove all duplicates one? Please let me know if there is any way.

share|improve this question
    
Does the order matter? In other words, is it necessary that the first occurrence of the character is the one you save? –  Lindrian Oct 10 '13 at 17:01
    
i want characters in same sequence after remove duplicates one. Only unique one. –  Mike Oct 10 '13 at 17:04

1 Answer 1

up vote 7 down vote accepted

A lookahead like "this, followed by something and this":

> str = "aaabbbccccabbbbcccccc"
"aaabbbccccabbbbcccccc"
> str.replace(/(.)(?=.*\1)/g, "")
"abc"

Note that this preserves the last occurrence of each character:

> str = "aabbccxccbbaa"
"aabbccxccbbaa"
> str.replace(/(.)(?=.*\1)/g, "")
"xcba"

Without regexes, preserving order:

> str.split("").filter(function(x, n, s) { return s.indexOf(x) == n }).join("")
"abcx"
share|improve this answer
    
I asked Mike but he has not answered yet. Your solution is the one I would have gone with, and if you need to preserve order, wouldn't str.split("").reverse().join("") do the trick? –  Lindrian Oct 10 '13 at 17:04
1  
by running this code... string is not coming in same seqeunce. if var str = "aaabbbcccaabbbcccaaaaaaaasa"; output = "bcsa" but i want something like abcs –  Mike Oct 10 '13 at 17:07
    
@Lindrian: yes, that, or some other method from blog.stevenlevithan.com/archives/mimic-lookbehind-javascript –  georg Oct 10 '13 at 17:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.