Get video id from youtube link - javascript

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];

Related

Regex YouTube shorts url javascript python

I am making a board where users can post text, photo, and YouTube video link
I am trying to generate embed url from different types of YouTube urls that user copy and paste.
thanks Stackoverflow gods, I almost got it but not 100%
my js regex for ajax call to api
const ytRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/
...
let video = $('#post-video').val();
if (ytRegex.test(video)) {
video = $('#post-video').val();
} else {
video = 0;
}
...
my python regex
video_receive = request.form['video_give']
video_id1 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/.+$", video_receive)
video_id2 = re.findall("(https?\:\/\/)?(www\.)?(youtu\.?be)\/.+$", video_receive)
video_id3 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/(shorts).+$", video_receive)
if video_id1 :
link = video_receive.split("=")[1]
embed = "https://www.youtube.com/embed/"
video = embed + link
elif video_id2:
link = video_receive.split("/")[3]
embed = "https://www.youtube.com/embed/"
video = embed + link
elif video_id3:
link = video_receive.split("/")[4]
embed = "https://www.youtube.com/embed/"
video = embed + link
else:
video = 1
I am targetting 3 example types of yt urls with variables video_id#
https://www.youtube.com/watch?v=bjkVUaFhwno
https://youtu.be/BEkxOupf9Zc
https://youtube.com/shorts/UZsysDAUHAY?feature=share
1 is for desktop share url for yt video and yt shorts
2 is mobile share url for yt video
3 is mobile share url for yt shorts
In my python code,
if video_id1 & elif video_id2 works fine but problem arise after I added elif video_id3
when I test with https://youtube.com/shorts/UZsysDAUHAY?feature=share
my code stores https://www.youtube.com/embed/share into db
It seems like if video_id1 is working on video_id3 format. I assume this because the testing url has = before share and if video_id1 has .split("=") condition.
when I delete ?feature=share from the testing url, my web page give me error(POST...500 (INTERNAL SERVER ERROR)) not even submitting to db due to ajax call error. but works with original testing url.
Please advise me where I am getting wrong with yt shorts url.
The regex you use for the first pattern will also match your shorts urls, simply just check for pattern 3 first.

How to properly read the url of attachments from messages?

I want it to read when someone sends an image or sends a link of an image like with Imgur and then log the attachments url to a channel.
I have tried using if(message.attachments.length > 0 || message.content.includes(message.attachments)) but that seemed to do absolutely nothing. I looked on the discord.js and it says that MessageAttachments is a collection of all attachments in one single message so I attempted to resolve it and then let it output the collection into a message but that also seemed to do nothing as well. No errors or anything.
This is my full code for when someone sends an image.
if(message.attachments.length > 0 || message.content.includes(message.attachments)){
var promise1 = Promise.resolve(message.attachments);
promise1.then(function(value) {
client.channels.find("name","picture-log").send(value)
});
//var att = new MessageAttachment();
//client.channels.find("name","picture-log").send(`${message.author.tag} sent an embed of` + att.url)
}
Well message.attachments does indeed return pictures or files, but only the ones uploaded to Discord directly.
So if you want to filter URLs you need to use the message.content, and find the links with regex or something like that.
I tried to make a regex for this (might not be perfect but should work):
function imgurLinks (message) {
return message.match(/https?:\/\/(www.|i.|)imgur\.com[^\s]+/g);
}
var links = imgurLinks("hey take a look at this: https://i.imgur.com/ecSWPgA.png");
console.log(links);
That function returns an array of imgur links, from there just see how many links there are (if any) and do something if there are.
client.channels.find("name","picture-log")
.send(`${message.author.tag} sent imgur links: ${links.join(" ")}`)

Print youtube video title script with just video ID provided

I'm doing a simple (not so simple for me) youtube BBCode that hides the embedded video in a dropdown, for when there's too many embedded videos, to not cause the web browser to lag trying to load them all at the same time.
I want the dropdown to display the video thumbnail (got that sorted) and title.
I don't know much about javascript, and the other questions and answers about this haven't worked for me. Example:Fetching YouTube video title from known video id Maybe I don't know how to implement it.
I just need the script to get the youtube vide title from the id and print it, really.
Edit: YouTube shut down the v2 API in 2015, take a look at the documentation of the new API v3 for a working code.
https://stackoverflow.com/a/30685729/753676
Copied from https://stackoverflow.com/a/10597710/753676
You can do this with plain JavaScript like this:
<script
type="text/javascript"
src="https://gdata.youtube.com/feeds/api/videos/videoid?v=2&alt=json-in-script&format=5&callback=getTitle">
</script>
And then:
function getTitle(data) {
var feed = data.feed;
var entries = feed.entry || [];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
}
}
Unfortunately, since version 3. This is no longer possible with the youtube API without auth.
You can use noembed however without Auth if you want to grab basic info about the video.
I.E http://noembed.com/embed?url=http%3A//www.youtube.com/watch%3Fv%3DbDOYN-6gdRE&callback=my_embed_function
The response is JSON.

Get Youtube Video ID From Link With 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.

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.

Categories

Resources