0

I created the YT Regexp to match the ID of the video and it works in the Regex service - regex101 but in the real code it doesn't detect the ID somehow. On the attached screenshot you can see that in the service there is existing an ID group in the match result however in the console isn't.

I'm wondering how it's possible? Maybe my regexp is incorrect or is it some Regex specific behavior?

I'll appreciate any help/info!

Here is the code: My regexp

const YT_ID_REGEXP = /(?:https?:\/\/(?:www)?\.?y(?:2u\.be|outu\.be|outube.com)\/)(?:watch\?v=)?([\w\d]+)/gim;

It recognizes the standard YT link such as: 
  http://www.youtube.com/watch?v=Kmiw4FYTg2U  
and the shortcuts like: 
  http://youtu.be/ZRX8984sc 
or 
  http://y2u.be/w7ejDZ8SWv8

The image that demonstrates the problem I prepared the playground & demo regex101 service demo

Velidan
  • 5,526
  • 10
  • 48
  • 86
  • Does this answer your question? [How do you access the matched groups in a JavaScript regular expression?](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression) – aaandri98 Aug 05 '21 at 07:21
  • you can find the code generator command from regex101, the code created there works as expected – aaandri98 Aug 05 '21 at 07:22
  • Thank you @aaandri98 but I'm interested in my own regex and would like to understand what exactly mistake I did – Velidan Aug 05 '21 at 07:53
  • 1
    the problem is simpler, and written in the [answer](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression) i linked before - you won't access the matched groups with the `match` function, you will need to use `matchAll` or `exec` and an iterator – aaandri98 Aug 05 '21 at 07:58
  • 1
    Thank you but It isn't the true reason for the issue. The problem was in the **global** flag. For example here the **match** captures groups and returns matches as the items array . `let str = '

    Hello, world!

    '; let tag = str.match(/<(.*?)>/); console.log(tag)`
    – Velidan Aug 05 '21 at 08:04

1 Answers1

2

When you are using the g flag with match it does not return the captured groups.

Try using exec instead. You can use named groups for convenience if you don't want to work with indexes.

var str = "some https://www.youtube.com/watch?v=cYXI344Siew YT link";

// adding ?<id> before the pattern of video id
var regx = /(?:https?:\/\/(?:www)?\.?y(?:2u\.be|outu\.be|outube.com)\/)(?:watch\?v=)?(?<id>[\w\d]+)/gmi

// Now to get the id directly
var {groups: { id }} = regx.exec(str);

console.log(id); 
//cYXI344Siew

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges#using_named_groups

Jayesh
  • 94
  • 4
  • Thank you @Jayesh. That's exactly what I missed in my situation because I didn't know about the nuance with the global flag – Velidan Aug 05 '21 at 08:00