查找字符串中不重复的字符 [英] Find the characters in a string which are not duplicated
本文介绍了查找字符串中不重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在JavaScript中创建一个函数,以删除字符串中所有重复的字母.到目前为止,我已经能够做到这一点:如果我有"anaconda"一词,则应在显示"cod"时将其显示为"anaconda".这是我的代码:
I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(unique.indexOf(string[i])==-1){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
推荐答案
我们现在还可以使用过滤器方法清理内容:
We can also now clean things up using filter method:
function removeDuplicateCharacters(string) {
return string
.split('')
.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
.join('');
}
console.log(removeDuplicateCharacters('baraban'));
工作示例:
这篇关于查找字符串中不重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文