How can I capture grouped matches using JavaScript regex?

Need help capturing groups in JavaScript regex for my Discord bot. Example:

const patt = /NOTE\s+(\w+)/g;
const outcome = patt.exec('NOTE sample');

Expecting [ ‘NOTE’, ‘sample’ ] as output.

The execution of your provided example returns an array where the entire match is in index 0 and the first capturing group is in index 1. Therefore, the output becomes [ ‘NOTE sample’, ‘sample’ ], not [ ‘NOTE’, ‘sample’ ]. If your intent is to limit your full match to exactly ‘NOTE’, you might adjust your regex to something like /^(NOTE)\s+(\w+)$/ if you want a full strict match starting from the beginning and ending at the target word. This practice helps ensure that the boundaries are clearly defined.

In working through a similar challenge, I found that understanding how JavaScript populates the returned array was crucial. I once mistakenly expected the full match to only return the literal portion but learned that it comprises the entire matched string, with subsequent indices corresponding to each capturing group. When I needed to cleanly separate data, I used a two-step process: first, getting the full match via exec and then processing individual groups independently. This approach also helped me handle cases when optional groups were present in the regex.

hey, js exec returns the full match at index0 and remaining capture groups afterwards. so if you only need the group, just access match[1]. hope that clears it up a bit!