> ## Content Index
> Fetch the complete content index at: https://irishdotnet.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to extract a YouTube video id from a url
- URL: https://irishdotnet.dev/how-to-extract-a-youtube-video-id-from-a-url/
- Published: 2018-08-01T05:27:00.000Z
- Updated: 2024-08-04T11:26:26.000Z
- Author: Richard Reddy
- Tags: JavaScript, C#

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:

- [Youtube.com](http://youtube.com/?ref=irishdotnet.dev)
- Youtu.be

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 "";
            }
```