GraphQL Operation Header in JS
Match GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.
Try it in the JS tester →Pattern
regexJS
(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{ (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("(query|mutation|subscription)\\s+(\\w+)?\\s*(?:\\([^)]*\\))?\\s*\\{", "g");
const input = "query GetUser($id: ID!) { user(id: $id) { name } }";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
(query|mutation|subscription) captures the operation type. \s+(\w+)? optionally captures the operation name (anonymous operations omit it). (?:\([^)]*\))? optionally matches a variables declaration `($var: Type)`. The trailing `\s*\{` matches the opening brace of the selection set.
Examples
Input
query GetUser($id: ID!) { user(id: $id) { name } }Matches
query GetUser($id: ID!) {
Input
mutation { createPost(title: "hi") { id } }Matches
mutation {
Input
// not graphqlNo match
—