Here's an interesting situation (or maybe not so uncommon): I'm trying to extract two specific capturing groups using JavaScript regex. The first group should consist of one or more digits (0-9), while the second group should consist of one or more word characters or hyphens (A-Z, 0-9, -), but for some reason, I can never seem to retrieve the latter group.
Important note: I have intentionally used the alternation (|
) character as I want to potentially match either one or the other
This is the code snippet I am currently working with:
var subject = '#/34/test-data'
var myregexp = /#\/(\d+)|\/([\w-]+)/;
var match = myregexp.exec(subject);
if (match != null && match.length > 1) {
console.log(match[1]); // successfully returns '34'
console.log(match[2]); // why does this return undefined instead of 'test-data'?
}
The strange thing is that Regex Buddy confirms the presence of two capturing groups and even highlights them correctly in the test phrase.
Could this issue be related to a problem in my JavaScript syntax?