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.
Related
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";
}
}
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];
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().
When I visit my url, my script will get the current URL and store it in a variable with
var currentURL = (document.URL);
I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:
www.mysite.com/XdAs2
so this is what would be stored in my variable currentURL and I'd like to take only the XdAs2 from it and store that into another variable. In addition, I'd like to know two other things.
Is document.URL the best way to get the current URL or will I have issues with some browsers?
If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you
Here's some pseudo code:
var currentURL = (document.URL); // returns http://myplace.com/abcd
var part = currentURL.split("/")[1];
alert(part); // alerts abcd
Basically:
1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question
2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()
Using jquery, you can do he following in order to access every inch of the current URL:
www.mysite.com/XdAs2?x=123
assuming you have the following url:
1- get the url in a jQuery object
var currentUrl = $(location)
2- access everything using the following syntax
var result = currentUrl.attr('YOUR_DESIRED_PROPERTY');
some common properties:
hostname => www.mysite.com
pathname => XdAs2
search => ?x=123
I hope this may help.
If you want everything after the host, use window.location.pathname
Following on from Mohammed's answer you can do the same thing in vanilla javascript:
var urlPath = location.pathname,
urlHost = location.hostname;
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.