20

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.

4

2 回答 2

47

像“这个,然后是一些东西和这个”这样的前瞻:

var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"

请注意,这会保留每个字符的最后一次出现:

var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"

没有正则表达式,保持顺序:

var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
  return s.indexOf(x) == n
}).join("")); // "abcx"

于 2013-10-10T17:00:18.940 回答
14

这是一个老问题,但在 ES6 中我们可以使用Sets。代码如下所示:

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

console.log(result);

于 2017-07-26T09:52:26.363 回答