javascript jQuery:从字符串中删除重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22127640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:30:33  来源:igfitidea点击:

jQuery: remove duplicates from string

javascriptjquerystringduplicatesduplicate-removal

提问by user2571510

I have string values that contain a list of items separated with a comma, e.g. the value could be val1,val2,val3,val1,val4,val3,val2,val5.

我有包含用逗号分隔的项目列表的字符串值,例如值可以是val1,val2,val3,val1,val4,val3,val2,val5

Is there an easy way I can remove all duplicates from such a string so that each value only appears once within the string ?

有没有一种简单的方法可以从这样的字符串中删除所有重复项,以便每个值在字符串中只出现一次?

E.g. in the above example I would like to get val1,val2,val3,val4,val5instead.

例如,在上面的例子中,我想得到val1,val2,val3,val4,val5

Many thanks in advance, Tim.

提前非常感谢,蒂姆。

回答by Awlad Liton

Make an array by split string and use unique()try like this:

通过拆分字符串创建一个数组并使用unique()尝试像这样:

 data = "val1,val2,val3,val4,val5";
 arr =  $.unique(data.split(','));
 data = arr.join(","); //get unique string back with 

live demo

现场演示