I have a list of 20 phrases that I want to count in an article.
Currently, I'm doing
let counts = phrases.map((phrase, idx) => {
phrase.usage = (articleBody.match(new RegExp(phrase.phrase, 'gi')) || []).length
return phrase
})
This requires me to do an expensive search each time. Is there some way to do it faster or all at once?
Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string. Parameters: The count() function has one compulsory and two optional parameters.
One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.
The goal is to calculate amount of occurrences of subStr in str. To do this, we use the formula: (a-b)/c, where a - length of str, b - length of str without all occurrences of subStr (we remove all occurrences of subStr from str for this), c - length of subStr.
You can use String.prototype.matchAll
const str = ['ocurrence 1, and..', 'ocurrence 2, and..', 'other phrases'];
const array = [...str.join ` `.matchAll(new RegExp('ocurrence', 'gi'))];
console.log(array.length); // 2
Edit: counting occurrences in one string;
const articleBody = 'ocurrence 1, and.. ocurrence 2, and... etc';
const array = [...articleBody.matchAll(new RegExp('ocurrence', 'gi'))];
console.log(array.length) // 2;
Edit 2:
Using a service worker
I created a text of 3000 words ("Lorem ipsum" generator).
main.js
if ("serviceWorker" in navigator) {
document.addEventListener("DOMContentLoaded", function () {
const phrases = [
{ text: "Lorem ipsum" },
{ text: "elementum mattis" },
];
phrases.map((phrase, index) => {
const phraseWorker = new Worker("phrase-match-sw.js");
phraseWorker.onmessage = function (oEvent) {
const { text, match } = oEvent.data;
phrases[index] = { text, match };
};
phraseWorker.postMessage({
article:
"Lorem ipsum dolor sit amet consectetur adipiscing elit sapien orci, ligula leo consequat mus tellus elementum mattis lacus maecenas curabitur, ",
phrase,
});
});
});
}
phrase-match-sw.js
onmessage = function (event) {
const { article, phrase } = event.data;
phrase.match = [...article.matchAll(new RegExp(phrase.text,"gi"))].length;
postMessage(phrase);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With