let text = "This is some sample text to test our function"; console.log(text.match('some'); // Will create an array with the index of the word in the text where it was matched // [ index: 4, ...]
If we are searching for just one word, this is fine. But if we are searching for more than one occurrences? Maybe we can use the
matchAll function? Let's say we want to search for all the spaces in the text:
console.log(text.matchAll(' ')); // Will result in a RegExpStringIterator object
matchAll function works as expected, but will give us an iterator. While this is correct, working with an iterator is a bit cumbersome. We need to use a for construct, track the occurrences ourselves and count.
There must be a simpler way, right?
As you maybe already guessed, the solution is the usage of the match function with a regular expression. If we look at our suggester input parameters in the chrome developer console, we will see the following:
The interesting part is that we can use regular expressions directly (not wrapped in a string):
console.log(text.match(/some/)); // This will produce the same result as text.match('some');
To collect all occurrences in a text (all match groups) we just need to add the according command to the regular expression:
console.log(text.match(/some/g); // Will produce an array ['some']
By the length of the array we can tell how many times our search string appeared in the given text. For my use case it means the following:
let matchedSpaces = text.match(/ /g); // Will produce an array of spaces [' ', ' ', ' ', ...] 8 in total console.log(matchedSpaces.lenght); // Will output 8
Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.