Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of times different terms occur in a string string with JavaScript?

Tags:

javascript

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?

like image 736
Shamoon Avatar asked Oct 01 '20 16:10

Shamoon


People also ask

How do I count how many times a string appears in another string?

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.

How do I count the number of times a word appears in a string Javascript?

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.

How do I count the number of times a substring appears in a string in Java?

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.


1 Answers

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);
};
like image 199
lissettdm Avatar answered Sep 20 '22 06:09

lissettdm