Remove duplicate characters from string

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

    We can remove the duplicate or similar elements in string using for loop and extracting string methods like slice, substring, substr

    Example if you want to remove duplicate elements such as aababbafabbb:

    var data = document.getElementById("id").value
    for(var i = 0; i < data.length; i++)
    {
        for(var j = i + 1; j < data.length; j++)
        {
            if(data.charAt(i)==data.charAt(j))
            {
                data = data.substring(0, j) + data.substring(j + 1);
                j = j - 1;
                console.log(data);
            }
        }
    }
    

    Please let me know if you want some additional information.

提交回复
热议问题