I’m trying to extract a specific part of a string using regex with capturing groups, but I’m having trouble accessing the captured content.
var textInput = "hello pattern_xyz"; // I need to get "xyz"
var result = /(?:^|\s)pattern_(.*?)(?:\s|$)/.exec(textInput);
console.log(result); // Shows: [" pattern_xyz", "xyz"] which looks correct
console.log(result[1]); // Shows: undefined (this is confusing)
console.log(result[0]); // Shows: pattern_undefined (this is weird)
I expected result[1] to contain the captured group content, but it’s showing as undefined. What’s the correct way to access the matched groups from a regex result in JavaScript? Am I missing something in how the exec method works with parentheses groups?
I’ve hit this before - it’s usually a console display issue, not your regex. Your regex is probably working fine. Try console.log(JSON.stringify(result)) instead of just console.log(result) to see the actual array structure. Also check that you’re not reassigning the result variable somewhere between the exec call and accessing result[1]. Your browser’s dev tools might be showing cached output too. Refresh the page or try console.table(result) to double-check what’s actually in the array.
Your regex looks fine. I just tested it with “hello pattern_xyz” and it works - result[1] gives me “xyz” like it should. Check if you’re accidentally changing the result object somewhere else in your code, or if this is running inside a loop that’s messing with the output. Also, if the string’s coming from an external source, make sure there aren’t any encoding issues. The exec method should definitely populate result[1] with your captured group when there’s a match.
that’s weird - your code looks fine to me. try logging the whole result object first to see what’s actually in there. also check for whitespace issues in your string. the regex is correct and result[1] should definitely give you “xyz”.