Gatsby graphql with regex as variable

Viewed 7130

I would like to use regex with graphql query variable.

This does't return results:

export const query = graphql`
  query(
    $episodes: String!
    ) {
    episodes: allMarkdownRemark(
      filter: { fields: { slug: { regex: $episodes } } }
    ) {
      edges {
        node {
          id
        }
      }
    }
  }
`;

However, this would work:

export const query = graphql`
  query() {
    episodes: allMarkdownRemark(
      filter: { fields: { slug: { regex: "/episodes/travel/" } } }
    ) {
      edges {
        node {
          id
        }
      }
    }
  }
`;

what's wrong?

1 Answers

Passing regex via query arguments should work, see the screenshot below. Make sure you're passing in the regex as string, not the actual regex. Also, you'll need to escape the middle slash:

    context: {
-     episodes: /episodes\/traveller/             <-- doesn't work
+     episodes: /episodes\/traveller/.toString()  <-- works
or    episodes: "/episodes\\/traveller/"          <-- also works
    }

Try it out in one of the graphiQL embed in this page enter image description here

Related