Created
September 29, 2012 20:00
-
-
Save wesleybliss/3805053 to your computer and use it in GitHub Desktop.
JavaScript Word Frequency + Some Options
This file contains 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
/** | |
* 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