Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex remove repeated characters from a string by javascript

Tags:

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.

like image 914
Simpal Kumar Avatar asked Oct 10 '13 16:10

Simpal Kumar


1 Answers

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"
like image 57
georg Avatar answered Sep 28 '22 16:09

georg