return the first non repeating character in a string in javascript

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

    Here's a Solution using Regex to replace all repeating characters and then returning the first character.

    function firstNonRepeat(str) {
    
       // Sorting str so that all repeating characters will come together & replacing it with empty string and taking first character using substr.
    
       var rsl = str.split('').sort().join('').replace(/(\w)\1+/g,'').substr(0,1);
    
       if(rsl) return rsl;
    
       else return 'All characters are repeated in ' + str;
    
    }
    
    console.log(firstNonRepeat('aaabcccdeeef'));
    console.log(firstNonRepeat('aaacbdcee'));
    console.log(firstNonRepeat('aabcbd'));

提交回复
热议问题