If you're allowing customers to save YouTube videos on your site and you'd like to extract out the video id when storing into your database you could try using either of these options below.

The thing to remember is that the YouTube url can be either:

and the Video Id can be appended as a querystring parameter or as the last segment of the url:

  • YouTubeUrl?v=videoId
  • YouTubeUrl/videoId

Using C#:

public string YouTubeVideoIdFromUrl(string url)
        {
            var uri = new Uri(url);
            var query = HttpUtility.ParseQueryString(uri.Query);
            if (query.AllKeys.Contains("v"))
            {
                return query["v"];
            }
            return uri.Segments.Last();
        }

Using JavaScript with regex

function youTubeVideoIdFromUrl (urlToParse){
                    if (urlToParse) {
                    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
                    var match = url.match(regExp);
                    if (match && match[2].length === 11) {
                        return match[2];
                    }
                }
                return "";
            }