Search code examples
javascriptregexurlyoutuberegex-group

Why Youtube URL ID Regex find the id in the Regex service but doesn't work in the real JS code?


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


Solution

  • 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