Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created September 29, 2012 20:00
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 wesleybliss/3805053 to your computer and use it in GitHub Desktop.
Save wesleybliss/3805053 to your computer and use it in GitHub Desktop.
JavaScript Word Frequency + Some Options
/**
* Find how often words appear in a string, optionally
* limiting to ones that occur with a given frequency.
*
* @param {String} searchString The sentence to search on.
* @param {Integer} frequency The frequency at which you want to find words with.
* @param {Boolean} caseSensitive Whether to use case sensitive searching.
* @param {Booolean} stripPunctuation If punctuation should be removed before parsing.
*/
var wordFrequency = function( searchString, frequency, caseSensitive, stripPunctuation ) {
searchString = ( caseSensitive ? searchString : searchString.toLowerCase() );
searchString = ( stripPunctuation ? searchString.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, '') : searchString );
var found = {},
words = searchString.split(' ');
words.map( function( word ) {
if ( word.length >= 1 ) {
if ( found[word] ) {
found[word]++;
}
else {
found[word] = 1;
}
}
});
if ( frequency ) {
for ( var word in found ) {
if ( found[word] != frequency ) {
delete found[word];
}
}
}
return found;
};
// Find words that appear exactly 2 times
var result = wordFrequency( 'The king is dead, long live the king', 2, false );
for ( var word in result ) {
console.log( word );
}
// Find the frequency of all words
var result = wordFrequency( 'The king, is dead, long live the king', false, false, true );
for ( var word in result ) {
console.log( word + ': ' + result[word] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment