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;
}

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

5 Comments

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 stackoverflow.com/questions/52909815/…
Wouldn't return str.match(/fly|flies/g).length; be easier?
@Andy - thanks. I was working on both answers with an annoying child in the background :)
@peterflanagan, would you count "butterfly/butterflies" etc in your occurance list? Or is it just the actual words "fly" and "flies"?
@andyI would count them too
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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.