skip to Main Content

I am trying to extract video id using regex. Here are some video url examples:

http://fast.wistia.net/embed/iframe/26sk4lmiix
https://support.wistia.com/medias/26sk4lmiix

My regex:

var rx = /https?://(.+)?(wistia.com|wi.st)/(medias|embed)/*/([^;?]+)/,
_m = url.match(rx)
if(_m && _m[4])return _m[4]
else return false;

Regiex is not quite correct and is returning for exmaple:

iframe/26sk4lmiix

3

Answers


  1. If you just want to extract the last portion of the URL path component via regex, then just match on the patttern [^/]+$:

    var url = "http://fast.wistia.net/embed/iframe/26sk4lmiix";
    var id = url.match(/[^/]+$/);
    console.log(id);

    You could also split the URL on forward slash, and retain the final component:

    var url = "http://fast.wistia.net/embed/iframe/26sk4lmiix";
    var parts = url.split("/");
    console.log(parts[parts.length-1]);
    Login or Signup to reply.
  2. Here is the code without using the regex pattern.

    function getVideoId(url) {
      return url.split("/").pop();
    }
    
    const url1 = "http://fast.wistia.net/embed/iframe/26sk4lmiix";
    console.log(getVideoId(url1));
    
    const url2 = "https://support.wistia.com/medias/26sk4lmiix";
    console.log(getVideoId(url2));
    

    Output of url1: 26sk4lmiix

    Output of url2: 26sk4lmiix

    Login or Signup to reply.
  3. If you want to keep your current group patterns intact, you may use

    /https?://([^/]+)?(wistia.(?:com|net)|wi.st)/(medias|embed)(?:/.*)?/([^;?]+)/
    

    The (.+)? is changed to ([^/]+)? to make sure the first group value is only matching within the hostname part.

    I changed (wistia.com|wi.st) to (wistia.(?:com|net)|wi.st) since you have such an example with wistia.net to match.

    The (?:/.*)? part makes sure you match anything before an expected value that is captured into Group 4.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search