Get Youtube Video ID From Link With JavaScript - javascript

Is there any way to get video id from youtube link.
I have a way in php script, but I need it in javascript.
Here is my php script
function get_youtube($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
For example I have a youtube video link
http://www.youtube.com/watch?v=fWNaR-rxAic&list=RD029I9Ar6upx34
then I get content of V variable = fWNaR-rxAic

The below function will return video id of the video if it is a valid youtube url or return false.
function matchYoutubeUrl(url){
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp.$1 : false ;
}

Try this piece of code
/*Function youtubeLinkParser parses youtube link for Video ID*/
function youtubeLinkParser(url) {
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];
} else {
return null;
}
}

The format of a Youtube link is the following:
http://www.youtube.com/watch?parameter=video_id&bunch_of_other_stuff
Now, I have, wrongly, assumed that all videos had a watch?v=
It turns out there can be a watch?list= and the v= comes near the end.
parameter can be v or list or something else for all I know. It doesn't matter.
So this excludes the ?v= (This was pointed out on the #jetpack channel on irc.mozilla.org:8443 by freaktechnik). We're left with v=
Another point is that pretty much every piece dealing with this assumes a length of 11 characters. Why ? Just because it is now ?
Let's say you have your URL and it is video_url. You can achieve getting your video_id using just two splits. I can do it in two splits because I spent just few hours working with JavaScript, but I'm sure someone more experienced can do it better.
EDIT:
video_id = video_url.split("v=")[1];
ampersand_pos = video_id.indexOf("&");
if (ampersand_pos != -1) {
video_id = video_id.substring(0, ampersand_pos)
}
Try it. It takes into account this:
youtube(dot)com/watch?list=WL2358B031ED8642DE&v=FyUrrAqso-M
And also this:
youtube(dot)com/watch?v=hUgCuFiZozc&feature=c4-overview&list=UUyNpwxYpMdYpw8CNqqv3Bdw

I found a simple way of doing it without using regex.
Note: this works with all types of playable urls.
I made a function which does it for you:
function getLink(url){
fetch('www.youtube.com/oembed?url=' + url).then(res => {
var thumbnailUrl = res.thumbnail_url;
var id = thumbnail_url.split('vi/')[1].substring(0, 11);
return id;}
)
}
console.log(getLink(your_url));
// here replace 'your_url' with your specified youtube url.
All this does is, it uses youtube api and passes your url as an parameter, and youtube take cares of the type of the url, so you dont have to worry about it. The next thing is, the function then takes the 'thumbnail_url' data from that api, and then splits the thumbnail's url accordingly to find the ID of the video.

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

Get video id from youtube link

i have this line:
token = videos.results[i].titlemay_link.split("?v=")[1];
videos.results[i].titlemay_link = the link to a youtube video en the split only returns the code.
now the problem is that some youtube links i get are links like this:
https://www.youtube.com/watch?v=1zO9nWgI_LY&feature=youtu.be
so the output i get is:
1zO9nWgI_LY&feature=youtu.be
this will not load the video in the embed player, how can i get rid of the
&feature=youtu.be
thanks!
token = videos.results[i].titlemay_link.split("?v=")[1];
token = token.split("&")[0];
But that won't be sufficient in most of the cases as youtube URLs gets complicated many times, here is a more roust method to fetch the youtube video ID
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}
These are the types of URLs supported
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
Add one more condition after you get token and check using .contains as below:
if(token.contains('&'))
token=token.split('&')[0];

JS: get hostname from url , regex not working

I am trying to get hostname from set of urls that my webapp can encounter with.
The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.
Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.
In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "")
and I want to keep only hostname ending atWebapp/.
Problem:
my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below
JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/
JS:
var getHost = function (url) {
return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
"http://localhost/Webapp/",
"http://localhost/Webapp/#",
"http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
"12.168.1.1:8080/Webapp/index.html#",
"https://localhost/Webapp/index.html#ab#bg",
"https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
$("<p/>").text(getHost(this)).appendTo($(".test"));
});
Use url.match(/https?:\/\/([^\/]+)/);
EDIT:
It returns an array where the 1st element is the host with protocol and the 2nd without.
You can try removing anything after the last slash (files and hash-es):
var getHost = function (url) {
return url.replace(/\/[^/]*?$/, '/');
};
And here's the updated fiddle.
There's a bit of a trick you can use to get the browser to extract the hostname for you.
var getHost = function (url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
};
It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().

how to get youtube video id from url

I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.
I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.
I need something that matches all these URL's:
http(s)://www.youtu.be/videoID
http(s)://www.youtube.com/watch?v=videoID
(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)
Any ideas which can be handled by the browser quick/efficient is greatly appreciated!
Try this:
var url = "...";
var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
see regex:
/
(?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
(?:w{3}\.)? // Optional sub-domain, if have, must be www.
youtu(?:be)? // The domain. Match 'youtu' and optionally 'be'.
\.(?:com|be) // the domain-extension must be .com or .be
(?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
/
Maybe you should look at the Youtube API and try to see if there is a way to get a videoID by parsing the URL though the API.
Look at this SO post:
Youtube API - Extract video ID
This could be quick:
var url = 'http://www.youtu.be/543221';
//http://www.youtube.com/watch?v=SNfYz6Yw0W8&feature=g-all-esi would work also
var a = url.split("v=")[1];
a = a != undefined ? a : url.split("youtu.be/")[1];
b = a.split("&")[0];
the variable c will have your id. Quick. The regex is nicer... harder to read though. I have modified my code to account for both.
There are too many kind:
latest short format: http://youtu.be/NLqAF9hrVbY
iframe: http://www.youtube.com/embed/NLqAF9hrVbY
iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4
any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be
(Source: How do I find all YouTube video ids in a string using a regex?)
The best way is limiting input-data.
Good luck
try this code
var url = "...";
var videoid = url.match((?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11}));
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
The Regex is from
YouTube video ID regex
you can do it easily using preg_match here is the example:$url = "http://www.youtube.com/watch?v=YzOt12co4nk&feature=g-vrec";
preg_match('/v=([0-9a-zA-Z]+)/', $url, $matches);
$vid = $matches[1];
Now you will have the video id as: $vid = YzOt12co4nk;
I found a simple way of doing it without using regex.
I made a function which does it for you:
function getLink(url){
fetch('www.youtube.com/oembed?url=' + url).then(res => {
var thumbnailUrl = res.thumbnail_url;
var id = thumbnail_url.split('vi/')[1].substring(0, 11);
return id;}
)
}
console.log(getLink(your_url));
// here replace 'your_url' with your specified youtube url.
All this does is, it uses youtube api and passes your url as an parameter, and youtube take cares of the type of the url, so you dont have to worry about it. The next thing is, the function then takes the 'thumbnail_url' data from that api, and then splits the thumbnail's url accordingly to find the ID of the video.

debug help with rare unexpected output in js

I have the following javascript on my page that is supposed to generate and go to a url instead of posting a form:
var tokenList = ["auto", "usate"];
var dirList = [];
function makeUrl(prov, manuf, model, price){
if (_addToken(prov)){
_joinTokens();
}
if (_addToken(manuf)){
_addToken(model);
_joinTokens();
}
if (price){
return _joinDirs() + "?prezzo=" + price;
}
return _joinDirs();
}
function _addToken(tok){
if (tok){
tokenList.push(tok.replace(/ /g,"_"));
return true;
}
return false;
}
function _joinTokens(){
dirList.push(tokenList.join('-'));
tokenList = [];
}
function _joinDirs(){
if (tokenList){
_joinTokens();
}
var url = '/' + dirList.join('/');
if (url.charAt(url.length-1) == '/'){
url = url.slice(0, -1);
}
return url;
}
It's triggered by this code:
$(document).ready(function(){
$('#navForm').submit(function() {
var prov = $("[name=select-provincia]").val();
var manuf = $("[name=select-marca]").val();
var model = $("[name=select-modello]").val();
var price = $("[name=select-prezzo]").val();
var url = makeUrl(prov, manuf, model, price);
window.location = url;
return false;
});
});
It's been a long while since I translated this code from its original python. I've been getting rare errors in my server logs occasionally that show users trying to visit strange urls that look almost like two urls concatenated. I haven't been able to ever duplicate such an error, but my best guess is that there is something going on with my javascript. The last two times I got this error I noticed that the user was using firefox 3.6 and iphone. Could this be some kind of browser incompatibility? Is there anything wrong with my javascript at all? Is the error just in userland?
For reference here is an example wrong url:
/auto-usate-pesaro_e_urbino/fiat-500//rimini/fiat-500?prezzo=13000
and two possible correct ones:
/auto-usate-pesaro_e_urbino/fiat-500?prezzo=13000
/auto-usate-rimini/fiat-500?prezzo=13000
Any unrelated suggestions for optimizing the code are welcome since I am bad at this.
Not sure it that's the case, but I think those strange URLs might be a result of appending the generated URL to the URL of the page being viewed. You are generating just the pathname part of the URL, not including the protocol and host name (http://foo.com) -- it's possible that some browsers are interpreting this path as relative to the current one. Try prepending the URL with the protocol and hostname.
You might also want to see this answer: Setting JavaScript window.location and follow the advice to write the URL to window.location.href.

Categories

Resources