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:17

    The most satisfactory and easy to understand answer is the following.

    function firstNotRepeatingCharacter(s) {
            
        const arr = s.split("");
    
        for(let i = 0; i < arr.length; i++){
            let chr = arr[i];
            if( arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i])){
                return arr[i]
            }            
        }
        
        return "_"
    }
    

    Explanation: It loops through all the characters of a string from forward and backward and then compares the values. If the index of both forward and backward search is true then it returns that character.

提交回复
热议问题