December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 20 | Counting the Number of a Specific Word with split() |
Suppose you want to add search functionality to your application that provides information on how many times a word has appeared in a text. You can use the includes() method to determine whether the word exists within the string. But it doesn’t tell you the frequency of the word’s appearance.
You want to create a function that counts the number of a specified word (in this case, “cougar”) and returns the total number it finds.
Divide the string into an array of substrings with the split() method, count the number of items in the array by reading its length property, and return the result:
| | const str = `Cougar is an adaptable, ... |
Read now
Unlock full access