charCodeAt vs Regex

Edit on GitHub

Compare regex vs charCodeAt for string manipulation

Setup

Tests

  • charCodeAt

    function charFreq(sentence) {
        return sentence.toLowerCase().split('').reduce(function(accum, char) {
            var charCode = char.charCodeAt();
            
            if (charCode >= 97 && charCode <= 122) {
                accum[char] = accum[char] ? accum[char] + 1 : 1;
            }
            
            return accum;
        }, {});
    }
    
    charFreq('Monimolimnion');
  • Regex

    function charFreq(sentence) {
        var str = sentence.toLowerCase().replace(/[^a-z+]+/g, '').split('');
    
        return str.reduce(function(accum, char) {
            accum[char] = accum[char] ? accum[char] + 1 : 1;
            return accum;
        }, {});
    }
    charFreq('Monimolimnion');