javascript - Removing duplicates in a comma-separated list with a regex? -
i'm trying figure out how filter out duplicates in string regular expression, string comma separated. i'd in javascript, i'm getting caught how use back-references.
for example:
1,1,1,2,2,3,3,3,3,4,4,4,5
becomes:
1,2,3,4,5
or:
a,b,b,said,said, t, u, ugly, ugly
becomes
a,b,said,t,u,ugly
why use regex when can in javascript code? here sample code (messy though):
var input = 'a,b,b,said,said, t, u, ugly, ugly'; var splitted = input.split(','); var collector = {}; (i = 0; < splitted.length; i++) { key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, ""); collector[key] = true; } var out = []; (var key in collector) { out.push(key); } var output = out.join(','); // output 'a,b,said,t,u,ugly'
p/s: 1 regex in for-loop trim tokens, not make them unique
Comments
Post a Comment