return the first non repeating character in a string in javascript

后端 未结 26 2482
清酒与你
清酒与你 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:18

    You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:

    function firstNonRepeatedCharacter(string) {
      for (var i = 0; i < string.length; i++) {
        var c = string.charAt(i);
        if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
          return c;
        }
      }
      return null;
    }
    

    Demo: http://jsfiddle.net/Guffa/Se4dD/

提交回复
热议问题