1

I am looking for the number of occurences of two different patterns in a string. I am looking for fly or flies. I am able to find the occurrence of one, but not sure how to check for 2 different strings.

My attempt so far is

const flyCount = str => {
   return (str.match(/fly/g) || str.match(/flies/g) || []).length;
}
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

2 Answers2

4
  1. Combine the regex expressions to find both words.

Note: use \b (word boundary) to find exact words. If the words can be a part of other words, remove the \b.

const flyCount = str =>
   (str.match(/\b(?:fly|flies)\b/g) || []).length;

const result = flyCount('Look how he flies. He can fly');

console.log(result);
  1. Or get the length of each expression and sum them:

const flyCount = str =>
   (str.match(/\bfly\b/g) || []).length + (str.match(/\bflies\b/g) || []).length;

const result = flyCount('Look how he flies. He can fly');

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • thanks! will mark as answer. was thinking that, but wasn't sure if there was a another way based on something I had seen yesterday https://stackoverflow.com/questions/52909815/regex-to-replace-two-separate-things-separately-in-one-replace/52909853?noredirect=1#comment92730394_52909853 – peter flanagan Oct 21 '18 at 17:39
  • 2
    Wouldn't `return str.match(/fly|flies/g).length;` be easier? – Andy Oct 21 '18 at 17:41
  • 2
    @Andy - thanks. I was working on both answers with an annoying child in the background :) – Ori Drori Oct 21 '18 at 17:43
  • 1
    @peterflanagan, would you count "butterfly/butterflies" etc in your occurance list? Or is it just the actual words "fly" and "flies"? – Andy Oct 21 '18 at 17:44
  • @andyI would count them too – peter flanagan Oct 21 '18 at 18:04
1

This can be done with the | regex operator. You may also want to consider adding the \b word boundary.

const flyCount = str => (str.match(/\b(?:fly|flies)\b/g) || []).length

console.log(flyCount('One fly, two flies'))
AndreasPizsa
  • 1,736
  • 19
  • 26