I want to return the video id from the video url of YouTube even for Shorts.
But I have got pattern which works for some few url which do not includes Shorts
^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*
Edit: It should work for the following urls:
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
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI
Thank You
This should work on the provided examples
(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))
https://regex101.com/r/5JhmpW/1 The actual video id should be the third capture group in each match.
You can use it in javascript like this:
let data = `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
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI`;
let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
let videoIds = [...data.matchAll(regex)].map(x => x[3]);
Or if you only expect one url at a time:
function getVideoId(url) {
let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
return regex.exec(url)[3];
}
keep in mind regex in javascript aren't stateless, running the same regex multiple times will cause it to iterate through the matches in the text (and eventually return NULL once it has reached the end), which is why the regex is re initialized on every call in this case. If no matches are found, it will also return null.