0

I've got this array of paragraphs. I need to see if a specific word is in the array by using Regex. I'm new to regex and so far I've tried

claims.forEach((d) => {
  const regexp = /[protein]+/i
  const result = d.match(regexp)
  console.log(result)
})

However this returns every occurrence of the word "protein" even if its first 3 letters.

How would I take out any occurrence of not just protein, but a list of words using Regex?

this is the array:

["UPDATE | Due to high demand, please allow extra time for your delivery Dismiss", "HIGH IN PROTEIN & FIBRE", "<160 CALORIES", "GLUTEN & PALM OIL FREE", "NUT BUTTER FILLED", "This nutty, chewy ball with a salty kick is danger…ng or afternoon, to satisfy those sweet cravings.", "High in Protein & Fibre", "<160 Calories", "Gluten & Palm Oil Free", "Nut Butter Filled", "Packed with protein, full of fibre and nutritional…erfect pick me up to energise and keep you going!", "158kcal\n9.2g Protein\nVegetarian\nGluten Free\nPalm Oil Free\nHigh in Fibre", "Almonds (26%), Cashews (18%), Brown Rice Syrup, Wh…vourings, Antioxidant: Natural Mixed Tocopherols.", " ", "  Kosher", "VEGAN", "VEGAN", "By signing up to our newsletter, you agree for you…rselves regarding Bounce Brands and its partners.", "Fuelling your day the natural way!"]
Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
  • 2
    `[]` means "any of the characters inside of the brackets". Why do you need regex to find a substring of a string? Just use `s.includes("word")` or `s.indexOf("word")`. If you want to respect word boundaries, then you could use regex, `s.match(/\bword\b/g)`. – ggorlen Jun 17 '21 at 16:29

1 Answers1

0

You may use includes and filter functions to get the result.

const results = claims.filter((d) => {
   d.toLowerCase().includes('protein')
})
console.log(results)

If you still want to use regex, you should remove [ & ]

  claims.forEach((d) => {
     const regexp = /protein/i
     const result = d.match(regexp)
     console.log(result)
  })
Oleg Imanilov
  • 2,416
  • 1
  • 12
  • 25
  • The question is asking for case-insensitivity (see the `i` at the end of the regex), which a plain `includes` does not satisfy. Please note that using `toLowerCase()` is not a globally-correct solution to enable case-insensitivity. – Andrew Morton Jun 17 '21 at 16:53
  • This doesn't take into consideration word boundaries either – Samathingamajig Jun 17 '21 at 16:53
  • [`localeCompare()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) would be a valid method for a good answer, whereas `.toLowerCase()` is not. – Andrew Morton Jun 17 '21 at 16:55
  • Thanks for the answer, How do I chain regex words together? – Shuib Abdillahi Jun 17 '21 at 19:57