Skip to content
Advertisement

How can I find the EXACT amount of matching words in a string?

for a project I’ve written a function which includes the following:

JavaScript

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement