简体   繁体   English

正则表达式通过javascript从字符串中删除重复的字符

[英]Regex remove repeated characters from a string by javascript

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.输出: abc这工作正常。

But if str = "aaabbbccccabbbbcccccc" then output is abcabc .但是如果str = "aaabbbccccabbbbcccccc"那么输出是abcabc Is there any way to get only unique characters or remove all duplicates one?有没有办法只获取唯一字符或删除所有重复字符? Please let me know if there is any way.请让我知道是否有任何方法。

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"

This is an old question, but in ES6 we can use Sets .这是一个老问题,但在 ES6 中我们可以使用Sets The code looks like this:代码如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM