26

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.

2
  • Does the order matter? In other words, is it necessary that the first occurrence of the character is the one you save? Commented Oct 10, 2013 at 17:01
  • i want characters in same sequence after remove duplicates one. Only unique one. Commented Oct 10, 2013 at 17:04

3 Answers 3

59

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"

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

4 Comments

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?
by running this code... string is not coming in same seqeunce. if var str = "aaabbbcccaabbbcccaaaaaaaasa"; output = "bcsa" but i want something like abcs
@Lindrian: yes, that, or some other method from blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
How would you preserve the first occurance?
14

This is an old question, but in ES6 we can use Sets. The code looks like this:

var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');

console.log(result);

Comments

0

All examples above ignore letter if it appears again later. For example string 'aaabbbcccaaa' will become just 'abc' not 'abca'. For this (preserve each multiple occurence) I used this function:

function removeSameLetters(str){
    return str.replace(/(.)\1+/g, '$1');
}
console.log(removeSameLetters('aaabbbcccaa'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.