return the first non repeating character in a string in javascript

后端 未结 26 2219
清酒与你
清酒与你 2020-12-30 09:04

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.

T

26条回答
  •  礼貌的吻别
    2020-12-30 09:22

    I came accross this while facing similar problem. Let me add my 2 lines. What I did is a similar to the Guffa's answer. But using both indexOf method and lastIndexOf.

    My mehod:

    function nonRepeated(str) {
       for(let i = 0; i < str.length; i++) {
          let j = str.charAt(i)
          if (str.indexOf(j) == str.lastIndexOf(j)) {
            return j;
          }
       }
       return null;
    }
    
    nonRepeated("aabcbd"); //c
    

    Simply, indexOf() gets first occurrence of a character & lastIndexOf() gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.

提交回复
热议问题