Removing duplicates in a comma-separated list with a regex?

前端 未结 5 1526
滥情空心
滥情空心 2020-12-18 07:45

I\'m trying to figure out how to filter out duplicates in a string with a regular expression, where the string is comma separated. I\'d like to do this in javascript, but I\

5条回答
  •  孤城傲影
    2020-12-18 08:05

    Why use regex when you can do it in javascript code? Here is sample code (messy though):

    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'
    

    p/s: that one regex in the for-loop is to trim the tokens, not to make them unique

提交回复
热议问题