Home > Article > Web Front-end > An example of string deduplication is shared
How to achieve string deduplication? Usually split the string into an array and then operate on the array.
var str = "aabdeegdcffdsf", result = [], tempStr = ""; var removeDuplicate = function ( str ){ var arr = str.split('');//把字符串分割成数组 //arr.sort();//排序 for(var i = 0; i < arr.length; i++){ if(arr[i] !== tempStr){ result.push(arr[i]); tempStr = arr[i]; }else{ continue; } } return result.join(""); } console.log(removeDuplicate(str)); //abdegdcfdsf
var removeDuplicate = function ( str ){ var arr = str.split('');//把字符串分割成数组 //arr.sort();//排序 for(var i = 0; i <arr.length; i++){ if(tempStr.indexOf(arr[i])>=0){continue; console.log(1) }else{//console.log(2) result.push(arr[i]); tempStr+=arr[i];console.log(tempStr); } } return result.join(""); }
I tried it and the results are as follows: abdegcfds
The above is the detailed content of An example of string deduplication is shared. For more information, please follow other related articles on the PHP Chinese website!