Skip to content

Instantly share code, notes, and snippets.

@Glench
Last active December 11, 2015 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Glench/4562550 to your computer and use it in GitHub Desktop.
Save Glench/4562550 to your computer and use it in GitHub Desktop.
Counting characters in a string for javascript
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;
}
@Glench
Copy link
Author

Glench commented Jan 18, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment