使用正则表达式删除逗号分隔列表中的重复项?

Geu*_*uis 5 javascript regex

我试图找出如何使用正则表达式过滤掉字符串中的重复项,其中字符串以逗号分隔.我想在javascript中执行此操作,但我已经开始关注如何使用反向引用.

例如:

1,1,1,2,2,3,3,3,3,4,4,4,5
Run Code Online (Sandbox Code Playgroud)

变为:

1,2,3,4,5
Run Code Online (Sandbox Code Playgroud)

要么:

a,b,b,said,said, t, u, ugly, ugly
Run Code Online (Sandbox Code Playgroud)

a,b,said,t,u,ugly
Run Code Online (Sandbox Code Playgroud)

Luk*_*man 7

为什么在javascript代码中使用正则表达式?这是示例代码(虽然凌乱):

var input = 'a,b,b,said,said, t, u, ugly, ugly';
var splitted = input.split(',');
var collector = {};
for (i = 0; i < splitted.length; i++) {
   key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, "");
   collector[key] = true;
}
var out = [];
for (var key in collector) {
   out.push(key);
}
var output = out.join(','); // output will be 'a,b,said,t,u,ugly'
Run Code Online (Sandbox Code Playgroud)

p/s:for循环中的一个正则表达式是修剪标记,而不是使它们唯一