Regex remove repeated characters from a string by javascript

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"

Leave a Comment