4

I have obtained these codes from other stackoverflow pages to correct youtube links but they dont work for my url:

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

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:

The youtube url is not valid

sheno
  • 273
  • 1
  • 5
  • 16

3 Answers3

4

You don't 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 however:

var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
Joren
  • 3,068
  • 25
  • 44
0
^(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 unsure about other youtube url formats, but you should be able to extract it with subgroup 3.

Robadob
  • 5,319
  • 2
  • 23
  • 32
0

in fact I had done a mistake:

var url = this.value;

should change into:

var url = this.val();

thanks to @hjpotter92

sheno
  • 273
  • 1
  • 5
  • 16