for a project I’ve written a function which includes the following:
JavaScript
x
11
11
1
var filtering_words = ['alpha', 'beta', 'gamma'];
2
3
//finding matching words
4
var prohibited_words = filtering_words;
5
for (var i = 0; i < prohibited_words.length; i++) {
6
if (value.indexOf(prohibited_words[i]) > -1) {
7
user_report['matching_words'].push(prohibited_words[i]);
8
user_report['matching_words_amount'] = user_report['matching_words'].length;
9
}
10
}
11
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.
JavaScript
1
15
15
1
var user_report = { matching_words: {} }
2
var value = 'lambdabetaalphabeta'
3
var filtering_words = ['alpha', 'beta', 'gamma'];
4
5
var prohibited_words = filtering_words;
6
for (var i = 0; i < prohibited_words.length; i++) {
7
var matches = (value.match(new RegExp(prohibited_words[i], 'ig')) || []).length
8
if (matches) {
9
var matching_words = user_report['matching_words'] || {};
10
matching_words[prohibited_words[i]] = matches
11
}
12
}
13
user_report['matching_words_amount'] = Object.keys(user_report['matching_words']).length
14
15
console.log(user_report)