Showing unique characters in a string only once

后端 未结 13 2347
-上瘾入骨i
-上瘾入骨i 2020-12-31 20:38

I have a string with repeated letters. I want letters that are repeated more than once to show only once. For instance I have a string aaabbbccc i want the result to be abc.

13条回答
  •  情歌与酒
    2020-12-31 21:05

    You can use a regular expression with a custom replacement function:

    function unique_char(string) {
        return string.replace(/(.)\1*/g, function(sequence, char) {
             if (sequence.length == 1) // if the letter doesn't repeat
                 return ""; // its not shown
             if (sequence.length == 2) // if its repeated once
                 return char; // its show only once (if aa shows a)
             if (sequence.length == 3) // if its repeated twice
                 return sequence; // shows all(if aaa shows aaa)
             if (sequence.length == 4) // if its repeated 3 times
                 return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
             // else ???
             return sequence;
        });
    }
    

提交回复
热议问题