Retrieving a YouTube video id from Embed Code using Javascript and PHP

Follow Me on Pinterest

Retrieving the YouTube video id.I have been working on a project and came across a feature in my website that would need to take YouTube embed code or even a url and extract the video id for storage in a database.

Originally I looked into a PHP implementation for this but I thought it pointless to escape the embed code, put it into a data object for an Ajax call and fire it to the server for consumption. The PHP implementation would look like this:

$code = '<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>';

$pattern = '%(?:https?://)?(?:www\.)?(?:youtu\.be/| youtube\.com(?:/embed/|/v/|/watch\?v=))([\w-]{10,12})[a-zA-Z0-9\< \>\"]%x';
$result = preg_match($pattern, $code, $matches);


This sucessfully extracts the expected url to the video and its video id and returns:

Array ( [0] =>" [1] => e8X3ACToii0 )

Instead of this I wanted to use Javascript to grab the same information.

That way I could just extract the video id, validate it/run any sanitising and return it to the server.

To do this I had to implement the same regular expression but with a Javascript implementation.

This is done using the RegExp function native to Javascript. The code is shown below:

//get the embed code
var code = '<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>';
//the pattern
var reg = new RegExp('(?:https?://)?(?:www\\.)?(?:youtu\\.be/|youtube\\.com(?:/embed/|/v/|/watch\\?v=))([\\w-]{10,12})', 'g');
//get matches found for the regular expression
var matches = reg.exec(code);
//check if we have found a match for a YouTube video
//will support legacy code, shortened urls and
if (matches){
	//found a video so get the video id
	var videoId = matches[1];
	//run code to upload the video id to the server here
	//no match was returned so we run error feedback to the user

Logging this to the console (console.log(matches)) now returns what we want:

["", "e8X3ACToii0"]

Success! We can now retrieve the video id and fire it over the server.

One thing I did trip up with when running this code is to make sure the backslashes are escaped as the Javascript parser will fail.

I hope you found this code useful.

Filed Under: Blog, Code Share
Tags: , , , , , , .
Bookmark: permalink.

Let me know what you think:

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>