Regex remove repeated characters from a string by javascript

前端 未结 2 845
别跟我提以往
别跟我提以往 2020-12-05 19:13

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

function RemoveDuplicates() {
    var str = \"aaabbbccc\";
    var          


        
相关标签:
2条回答
  • 2020-12-05 19:33

    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"

    0 讨论(0)
  • 2020-12-05 19:33

    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);

    0 讨论(0)
提交回复
热议问题