Home >Web Front-end >JS Tutorial >How to remove duplicate characters from JavaScript string_javascript tips

How to remove duplicate characters from JavaScript string_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:23:361112browse

This chapter introduces how to delete repeated characters in a string. Regardless of whether it has actual value, it is quite good to regard it as a kind of learning about algorithms.

The code is as follows:

function dropRepeat(str){
 var result=[];
 var hash={};
 for(var i=0, elem; i<str.length;i++){
  elem=str[i];
  if(!hash[elem]){
   hash[elem]=true;
   result=result+elem;
  }
 }
 return result;
}

The function in the above code can delete repeated characters in the string, usage example:

dropRepeat("abcdd") 

The return value is: abcd.

Let me share with you Python: remove repeated characters in a string

python 2.7:
#-*- encoding:utf-8 -*-
string = 'abc123456ab2s'
r = ''.join(x for i, x in enumerate(string) if string.index(x) == i)
print string
print r

The output is as follows:

abc123456ab2s
abc123456s

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn