views:

502

answers:

4

Hi,

In Jquery i want to check the specific url from youtube alone and show success status and others i want to skip by stating it as not valid url

var _videoUrl = "youtube.com/watch?v=FhnMNwiGg5M";
if (_videoUrl.contains("youtube.com"))
{
  alert('Valid'); 
} 
else
{ 
  alert('Not Valid');
} 

how to check with contains. or any other option to check the valid youtube url alone.

A: 

You may try using a regular expression:

var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var isyouTubeUrl = /((http|https):\/\/)?(www\.)?(youtube\.com)(\/)?([a-zA-Z0-9\-\.]+)\/?/.test(url);
Darin Dimitrov
tanq all for ur answers its working fine
kart
A: 

Assuming you want a Youtube video URL rather than any YouTube URL, you can do it using a regex:

var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var matches = url.match(/^(https?:\/\/)?([^\/]*\.)?youtube\.com\/watch\?([^]*&)?v=\w+(&[^]*)?/i);
Max Shawabkeh
+1  A: 

Typically, the thing that most people want is the youtube video ID. To simply match this, use the following regex.

var matches = _videoUrl.match(/watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches)
{
    alert('valid');
}

Naturally, the regex could be expanded to include the entire youtube url, but if all you need is the ID, this is the most surefire way I've found.

Soviut
Don't forget that video ID is always 11 characters long....You must check that the video ID length is of length 11.
The Elite Gentleman
Good to know, although I tend to allow any length simply because the ID length could change if they run out of IDs.
Soviut
+1  A: 

I found this from the closure library, might be handy:

/**
 * A youtube regular expression matcher. It matches the VIDEOID of URLs like
 * http://www.youtube.com/watch?v=VIDEOID.
 * @type {RegExp}
 * @private
 */
goog.ui.media.YoutubeModel.matcher_ =
    /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i;
David