Remove duplicate characters from string

前端 未结 28 948
猫巷女王i
猫巷女王i 2020-12-01 13:09

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

28条回答
  •  甜味超标
    2020-12-01 13:45

    I have 3 loopless, one-line approaches to this.

    Approach 1 - removes duplicates, and preserves original character order:

    var str = "anaconda";
    var newstr = str.replace(new RegExp("[^"+str.split("").sort().join("").replace(/(.)\1+/g, "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")+"]","g"),"");
    //cod
    

    Approach 2 - removes duplicates but does NOT preserve character order, but may be faster than Approach 1 because it uses less Regular Expressions:

    var str = "anaconda";
    var newstr = str.split("").sort().join("").replace(/(.)\1+/g, "");
    //cdo
    

    Approach 3 - removes duplicates, but keeps the unique values (also does not preserve character order):

    var str = "anaconda";
    var newstr = str.split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
    //acdno
    

提交回复
热议问题