JimmyBanks
JimmyBanks

Reputation: 4708

Get YouTube ID using JavaScript .match()

So I have a working preg_match in PHP, however, for the life of me, I cannot get the same function to work using Javascript/jQuery.

This is what I am stuck on currently:

yt=$('#yt').val().match(/~^\(?:https?://\)?(?:www\.)?(?:youtube\.com|youtu\.be)(?:/)(?:watch\?v=)?([^&]+)~x/);
alert(yt[1]);

This is the working function in PHP:

$rx = "~"
."^(?:https?://)?"             // Optional protocol
."(?:www\.)?  "                // Optional subdomain
."(?:youtube\.com|youtu\.be)"  // Mandatory domain name
."(?:/)"                //mandatory bracket
."(?:watch\?v=)?"       //optional URI
."([^&]+)"           //video id as capture group 1
."~x";

$has_match = preg_match($rx, $url, $matches);

Any idea how to get this functioning?

I found some similar posts on Stack, but they are far less complex than this regex, and couldnt get my head wrapped around the differences.

Upvotes: 0

Views: 140

Answers (1)

FabianCook
FabianCook

Reputation: 20567

Not 100% sure but I think you haven't escaped everything correctly.

yt=$('#yt').val().match("^(?:https?://)?(?:www\.)?(?:youtube\.com|youtu\.be)(?:/)(?:watch\?v=)?([^&]+)")
alert(yt[1]);

"https://www.youtube.com/watch?v=dQw4w9WgXcQ".match("^(?:https?://)?(?:www\.)?(?:youtube\.com|youtu\.be)(?:/)(?:watch\?v=)?([^&]+)");

results in

["https://www.youtube.com/watch?v=iQbS-8m3svw", "watch?v=dQw4w9WgXcQ"]

Upvotes: 2

Related Questions