How to count the number of matches in the text?

  • 0
    For example, text:
    “The British monopolized Bengal's foreign trade, as well as the most important branches of Bengal's internal trade. Hundreds of thousands of Bengali artisans were forcibly attached to the company's trading posts, where they had to deliver their products at minimal prices. Taxes have skyrocketed. '

    Only the includes method comes to mind, but when you enter, for example, the word "bargaining", the number of matches should be 2.
    JavaScript Anastasia Robbins, Oct 20, 2020

  • 2 Answers
  • 0
    text.match (RegExp (str, 'g')) ?. length ?? 0



    or



    text.split (str) .length - 1
    Anonymous

  • 0
    So?

    Nicholas Foley

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!