0

I have found examples of a Regex that will match if a string does not contain a particular word. But I am looking for something that will match if it contains a word AND not another word. Example:

I'm dealing with URL exclusions based off of RegEx. I would like it to match if the URL contains collections and not products

The Regex I have found to work if it does not contain products is this: ^((?!products).)*$ Works great but any time I add in a check to make sure it has collections in it, it fails every time.

Here is a sample url I would like it not to match:

https://dummysite.com/collections/frontpage/products/myproduct

But if it were:

https://dummysite.com/collections/frontpage/

It should match.

How do I solve this problem?

Emma
  • 26,487
  • 10
  • 35
  • 65
Xandor
  • 448
  • 1
  • 7
  • 19
  • 1
    I won't recommend using RegEx for this simple case. It's slow. Try ES6 `includes()`. – k3llydev May 21 '19 at 18:19
  • 1
    @k3llydev I agree 100% but unfortunately have no control over that getting used. It only happens once per page load anyways, so not a huge deal. – Xandor May 21 '19 at 18:36

1 Answers1

2

You can use positive lookahead

(?!.*products)(?=.*collections)
      |               |___________  Positive lookahead ( For must condition)
      |___________________________  Negative lookahead ( For must not condition)

let urls = ['https://dummysite.com/collections/frontpage/products/myproduct','https://dummysite.com/collections/frontpage/']

urls.forEach(url=>{
  console.log(url, '\nResult --->', /^(?!.*products)(?=.*collections).*$/.test(url))
})
Code Maniac
  • 35,187
  • 4
  • 31
  • 54