Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

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

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'm getting caught up with how to use the 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...