YouTube Video ID from URL

I got these codes from other stackoverflow pages to fix youtube links, but they do not work for my URL:

https://www.youtube.com/watch?v=r2dRQHJ-aAk 

the code:

 <script> $('#videoURL').focusout(function() { var url = this.value; var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/); if(videoid != null) { $('#videoURL').value('http://www.youtube.com/watch?v='+videoid[1]); } else { console.log("The youtube url is not valid."); } }); </script> 

it always returns:

Invalid youtube url

+4
source share
3 answers

You do not need a regular expression for this:

 var videoid = url.split('v=')[1]; var ampersandPosition = videoid.indexOf('&'); if(ampersandPosition != -1) { videoid = video_id.substring(0, ampersandPosition); } 

You can use it if you want:

 var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
+4
source
 ^(https?://(www\.)?)?youtube\.com/watch\?v=([0-9a-zA-Z\-]{11})$ 

Works for;

 https://www.youtube.com/watch?v=r2dRQHJ-aAk https://youtube.com/watch?v=r2dRQHJ-aAk http://www.youtube.com/watch?v=r2dRQHJ-aAk youtube.com/watch?v=r2dRQHJ-aAk 

I'm not sure about the other youtube URL formats, but you should be able to extract them from subgroup 3.

0
source

I actually made a mistake:

 var url = this.value; 

should change to:

 var url = this.val(); 

thanks @ hjpotter92

0
source

Source: https://habr.com/ru/post/1493754/


All Articles