Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  190] [ 4]  / answers: 1 / hits: 40944  / 11 Years ago, thu, october 10, 2013, 12:00:00

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



function RemoveDuplicates() {
var str = aaabbbccc;
var filtered = str.replace(/[^ws]|(.)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.


More From » regex

 Answers
11

A lookahead like this, followed by something and this:





var str = aaabbbccccabbbbcccccc;
console.log(str.replace(/(.)(?=.*1)/g, )); // abc





Note that this preserves the last occurrence of each character:





var str = aabbccxccbbaa;
console.log(str.replace(/(.)(?=.*1)/g, )); // xcba





Without regexes, preserving order:





var str = aabbccxccbbaa;
console.log(str.split().filter(function(x, n, s) {
return s.indexOf(x) == n
}).join()); // abcx




[#75085] Wednesday, October 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
michaelashelbieh

Total Points: 303
Total Questions: 139
Total Answers: 97

Location: Suriname
Member since Sun, Oct 17, 2021
3 Years ago
;