Home > Web Front-end > JS Tutorial > body text

How to remove duplicate characters from JavaScript string_javascript tips

WBOY
Release: 2016-05-16 15:23:36
Original
1093 people have browsed it

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;
}
Copy after login

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

dropRepeat("abcdd") 
Copy after login

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
Copy after login

The output is as follows:

abc123456ab2s
abc123456s

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template