Remove duplicate characters from string

前端 未结 28 935
猫巷女王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:40

    function removeDup(str) {
      var arOut = [];
      for (var i=0; i < str.length; i++) {
        var c = str.charAt(i);
        if (c === '_') continue;
        if (str.indexOf(c, i+1) === -1) {
          arOut.push(c);
        }
        else {
          var rx = new RegExp(c, "g");
          str = str.replace(rx, '_');
        }
      }
      return arOut.join('');
    }
    

提交回复
热议问题