for a project I’ve written a function which includes the following:
var filtering_words = ['alpha', 'beta', 'gamma']; //finding matching words var prohibited_words = filtering_words; for (var i = 0; i < prohibited_words.length; i++) { if (value.indexOf(prohibited_words[i]) > -1) { user_report['matching_words'].push(prohibited_words[i]); user_report['matching_words_amount'] = user_report['matching_words'].length; } }
String: ‘alpha beta beta gamma’
For now I just get all the matching words. So my result would look like that: [‘alpha’], [‘beta’], [‘gamma’]
But I would also like to know how often a “filtering_word” is in my string. In this case I would want to know that there are actually 2 betas…
Any idea?
Cheers
Advertisement
Answer
Store the results in an Object
instead of an Array
, so that you could map the filtered word to the number of occurrences.
To find the number of occurrences, use a RegExp
with the g
flag to get an array of all occurrences (and i
flag for a case insensitive search), then get the resulting array length.
var user_report = { matching_words: {} } var value = 'lambdabetaalphabeta' var filtering_words = ['alpha', 'beta', 'gamma']; var prohibited_words = filtering_words; for (var i = 0; i < prohibited_words.length; i++) { var matches = (value.match(new RegExp(prohibited_words[i], 'ig')) || []).length if (matches) { var matching_words = user_report['matching_words'] || {}; matching_words[prohibited_words[i]] = matches } } user_report['matching_words_amount'] = Object.keys(user_report['matching_words']).length console.log(user_report)