Last active
December 11, 2015 06:58
-
-
Save Glench/4562550 to your computer and use it in GitHub Desktop.
Counting characters in a string for javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function charCount(str) { | |
if (!str || typeof str !== 'string') { | |
throw 'must provide a string'; | |
} | |
var letter, | |
countObj = {}, | |
alphabeticalLetters = [], | |
outputString = '', | |
letterCount; | |
for (var i=0; i < str.length; ++i) { | |
letter = str[i]; | |
if (letter in countObj) { | |
countObj[letter] += 1; | |
} else { | |
countObj[letter] = 1; | |
alphabeticalLetters.push(letter); | |
} | |
} | |
alphabeticalLetters.sort(); | |
for (i = 0; i < alphabeticalLetters.length; ++i) { | |
letter = alphabeticalLetters[i]; | |
letterCount = countObj[letter]; | |
if (letter === ' ') { | |
outputString += "'" + letter + "'" + ':' + letterCount + ' '; | |
} else { | |
outputString += letter + ':' + letterCount + ' '; | |
} | |
} | |
return outputString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use with google spreadsheets go to Drive homepage, click Create -> More -> Script and paste the above contents. Then in a spreadsheet use by doing =charCount(A1) in a cell.