SoFunction
Updated on 2025-02-28

How to delete duplicate characters in JavaScript string

This chapter introduces how to delete duplicate characters in a string. Regardless of whether it has actual value or not, it is also good to treat it as a learning of algorithms.

The code is as follows:

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

The functions in the above code can delete duplicate characters in a string, use examples:

dropRepeat("abcdd") 

The return value is:abcd.

Let me share with you Python: Remove duplicate characters from strings

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

The output is as follows:

abc123456ab2s
abc123456s