Comment puis-je obtenir L'ID de la vidéo YouTube à partir d'une URL?
je veux obtenir le v=id
de L'URL de YouTube avec JavaScript (no jQuery, pur JavaScript).
exemple de formats D'URL YouTube
http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/watch?v=u8nQa1cJyX8
ou tout autre format YouTube qui contient un ID de vidéo dans l'URL.
résultat de ces formats
u8nQa1cJyX8
30 réponses
Vous n'avez pas besoin d'utiliser une expression régulière pour cela.
var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}
j'ai fait une amélioration à Regex fourni par" jeffreypriebe " parce qu'il avait besoin d'une sorte D'URL YouTube est l'URL des vidéos quand ils regardent à travers un canal.
et Bien non, mais c'est la fonction que j'ai armés.
<script type="text/javascript">
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;
}
</script>
ce sont les types D'URL pris en charge
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
peut être trouvé dans [http://web.archive.org/web/20160926134334/] http://lasnv.net/foro/839/Javascript_parsear_URL_de_YouTube
J'ai simplifié Un peu la réponse de Lasnv.
il corrige également le bug décrit par WebDeb.
le voici:
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
//error
}
voici un lien de regexer pour jouer avec: http://regexr.com/3dnqv
aucun de ceux-ci ne fonctionnait sur l'évier de cuisine à partir du 1/1/2015, notamment les URLs sans protocole http/s et avec youtube-nocookie domaine. Voici donc une version modifiée qui fonctionne sur toutes ces différentes versions de Youtube:
// Just the regex. Output is in [1].
/^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/
// For testing.
var urls = [
'//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
'http://youtu.be/6dwqZw0j_jY',
'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
'http://youtu.be/afa-5HQHiAs',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
'http://www.youtube.com/watch?v=peFZbP64dsU',
'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
];
var i, r, rx = /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/;
for (i = 0; i < urls.length; ++i) {
r = urls[i].match(rx);
console.log(r[1]);
}
/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/
testé le:
- http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
- http://www.youtube.com/embed/0zM3nApSvMg?rel=0
- http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
- http://www.youtube.com/watch?v=0zM3nApSvMg
- http://youtu.be/0zM3nApSvMg
- http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
- http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ
- http://youtu.be/dQw4w9WgXcQ
- http://www.youtube.com/embed/dQw4w9WgXcQ
- http://www.youtube.com/v/dQw4w9WgXcQ
- http://www.youtube.com/e/dQw4w9WgXcQ
- http://www.youtube.com/watch?v=dQw4w9WgXcQ
- http://www.youtube.com/?v=dQw4w9WgXcQ
- http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
- http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
- http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
- http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0
inspiré par cette autre réponse .
j'ai créé une fonction qui teste une entrée utilisateur pour Youtube, Soundcloud ou vimeo embed ID, pour être en mesure de créer un design plus continu avec des médias intégrés. Cette fonction détecte et renvoie un objet avec deux propriétés: "type" et "id". Type peut être "youtube", "vimeo" ou "soundcloud" et la propriété "id" est l'unique id de média.
sur le site j'utilise un dump textarea, où l'utilisateur peut coller dans n'importe quel type de lien ou de code intégré, y compris le imrame-embedding de vimeo et youtube.
function testUrlForMedia(pastedData) {
var success = false;
var media = {};
if (pastedData.match('http://(www.)?youtube|youtu\.be')) {
if (pastedData.match('embed')) { youtube_id = pastedData.split(/embed\//)[1].split('"')[0]; }
else { youtube_id = pastedData.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
media.type = "youtube";
media.id = youtube_id;
success = true;
}
else if (pastedData.match('http://(player.)?vimeo\.com')) {
vimeo_id = pastedData.split(/video\/|http:\/\/vimeo\.com\//)[1].split(/[?&]/)[0];
media.type = "vimeo";
media.id = vimeo_id;
success = true;
}
else if (pastedData.match('http://player\.soundcloud\.com')) {
soundcloud_url = unescape(pastedData.split(/value="/)[1].split(/["]/)[0]);
soundcloud_id = soundcloud_url.split(/tracks\//)[1].split(/[&"]/)[0];
media.type = "soundcloud";
media.id = soundcloud_id;
success = true;
}
if (success) { return media; }
else { alert("No valid media id detected"); }
return false;
}
étant donné que YouTube a une variété de styles D'URL, Je pense Regex est une meilleure solution. Voici mon Regex:
^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*
Groupe 3 a votre ID YouTube
exemples D'URL YouTube (actuellement, y compris "legacy embed URL style") - le Regex ci-dessus fonctionne sur chacun d'eux:
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
astuce Chapeau à Lasnv
code Java: (fonctionne pour toutes les 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/embed/0zM3nApSvMg?rel=0 "
- http://www.youtube.com/watch?v=0zM3nApSvMg
- http://youtu.be/0zM3nApSvMg
- http://www.youtube.com/watch?v=0zM3nApSvMg /
- http://www.youtube.com/watch?feature=player_detailpage&v=8UVNT4wvIGY
)
String url = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";
String regExp = "/.*(?:youtu.be\/|v\/|u/\w/|embed\/|watch\?.*&?v=)";
Pattern compiledPattern = Pattern.compile(regExp);
Matcher matcher = compiledPattern.matcher(url);
if(matcher.find()){
int start = matcher.end();
System.out.println("ID : " + url.substring(start, start+11));
}
Pour DailyMotion:
String url = "http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun";
String regExp = "/video/([^_]+)/?";
Pattern compiledPattern = Pattern.compile(regExp);
Matcher matcher = compiledPattern.matcher(url);
if(matcher.find()){
String match = matcher.group();
System.out.println("ID : " + match.substring(match.lastIndexOf("/")+1));
}
puisque L'ids De La vidéo YouTube est réglé pour être 11 caractères , nous pouvons simplement substring
après avoir divisé l'url avec v=
.
Alors nous ne dépendons pas de l'ampersand à la fin.
var sampleUrl = "http://www.youtube.com/watch?v=JcjoGn6FLwI&asdasd";
var video_id = sampleUrl.split("v=")[1].substring(0, 11)
simple et sympathique :)
j'ai résumé toutes les suggestions et voici la réponse universelle et brève à cette question:
if(url.match('http://(www.)?youtube|youtu\.be')){
youtube_id=url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
}
version légèrement plus stricte:
^https?://(?:www\.)?youtu(?:\.be|be\.com)/(?:\S+/)?(?:[^\s/]*(?:\?|&)vi?=)?([^#?&]+)
testé le:
http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel
en retard pour le match ici, mais j'ai rassemblé deux excellentes réponses de mantish et j-W. Premièrement, le regex modifié:
const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/
voici le code de test (j'ai ajouté les cas de test originaux de mantish aux plus méchants de j-w):
var 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',
'//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
'http://youtu.be/6dwqZw0j_jY',
'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
'http://youtu.be/afa-5HQHiAs',
'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
'http://www.youtube.com/watch?v=peFZbP64dsU',
'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
];
var failures = 0;
urls.forEach(url => {
const parsed = url.match(youtube_regex);
if (parsed && parsed[2]) {
console.log(parsed[2]);
} else {
failures++;
console.error(url, parsed);
}
});
if (failures) {
console.error(failures, 'failed');
}
une version légèrement modifiée de la one mantish posté:
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]{11,11}).*/;
var match = url.match(regExp);
if (match) if (match.length >= 2) return match[2];
// error
cela suppose que le code est toujours de 11 caractères. Je l'utilise dans ActionScript, Je ne suis pas sûr que {11,11} soit pris en charge dans Javascript. A également ajouté le support pour &v=.... (au cas où)
un de plus:
var id = url.match(/(^|=|\/)([0-9A-Za-z_-]{11})(\/|&|$|\?|#)/)[2]
il fonctionne avec N'importe quelle URL montrée dans ce thread.
ça ne marchera pas quand YouTube ajoute un autre paramètre avec 11 caractères base64. Jusque là, il est le moyen le plus facile.
j'ai aimé la réponse de Surya.. Juste un cas où ça ne marchera pas...
String regExp = "/.*(?:youtu.be\/|v\/|u/\w/|embed\/|watch\?.*&?v=)";
ne fonctionne pas pour
youtu.be/i4fjHzCXg6c and www.youtu.be/i4fjHzCXg6c
mise à jour de la version:
String regExp = "/?.*(?:youtu.be\/|v\/|u/\w/|embed\/|watch\?.*&?v=)";
ça marche pour tous.
essayez celui - ci -
function getYouTubeIdFromURL($url)
{
$pattern = '/(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})/i';
preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : false;
}
Chris Nolet cleaner exemple de réponse Lasnv est très bon, mais j'ai récemment découvert que si vous essayez de trouver votre lien youtube dans le texte et mettre un texte aléatoire après l'url youtube, regexp correspond beaucoup plus que nécessaire. Amélioration de la réponse de Chris Nolet:
/^.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]{11,11}).*/
function parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[8].length==11){
alert('OK');
}else{
alert('BAD');
}
}
Pour les essais de:
https://www.youtube.com/embed/vDoO_bNw7fc - attention first symbol «v» in «vDoO_bNw7fc»
http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel
Cela nécessite certainement regex:
copie dans Ruby IRB:
var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
url.match(VID_REGEX)[1]
voir pour tous les cas d'essai: https://gist.github.com/blairanderson/b264a15a8faaac9c6318
tl; dr.
correspond à tous les exemples D'URL sur cette question et puis quelques.
let re = /^(https?:\/\/)?((www\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)/i;
let id = "https://www.youtube.com/watch?v=l-gQLqv9f4o".match(re)[7];
ID sera toujours dans le groupe de match 7.
exemples en direct de toutes les URLs que j'ai trouvées dans les réponses à cette question: https://regexr.com/3u0d4
explication complète:
comme beaucoup de réponses / commentaires ont soulevé, il existe de nombreux formats pour la vidéo youtube URL. Même plusieurs TLD où ils peuvent sembler être "hébergés".
vous pouvez consulter la liste complète des variations que j'ai vérifiées en suivant le lien regexr ci-dessus.
permet de décomposer le RegExp.
^
Verrouiller la chaîne au début de la chaîne.
(https?:\/\/)?
Protocoles facultatifs http:// ou https: / / le ?
rend l'article précédent facultatif de sorte que le s
et puis le groupe entier (n'importe quoi inclus dans un ensemble de parenthèses) sont optionnels.
Ok, cette partie suivante est la viande de celui-ci. Fondamentalement, nous avons deux options, les différentes versions de www.youtube.com / ... [id] et le lien raccourci youtu.Version be / [id].
( // Start a group which will match everything after the protocol and up to just before the video id.
(www\.)? // Optional www.
(youtube(-nocookie)?|youtube.googleapis) // There are three domains where youtube videos can be accessed. This matches them.
\.com // The .com at the end of the domain.
.* // Match anything
(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/) // These are all the things that can come right before the video id. The | character means OR so the first one in the "list" matches.
| // There is one more domain where you can get to youtube, it's the link shortening url which is just followed by the video id. This OR separates all the stuff in this group and the link shortening url.
youtu\.be\/ // The link shortening domain
) // End of group
enfin, nous avons le groupe pour sélectionner l'ID de la vidéo. Au moins un caractère qui est un nombre, une lettre, un trait de soulignement ou un tiret.
([_0-9a-z-]+)
, Vous pouvez trouver beaucoup plus de détails sur chaque partie de le regex en pointant sur le lien regexr et en voyant comment chaque partie de l'expression correspond au texte de l'url.
Eh bien, la façon de le faire avec simple parsing serait: tout commencer après le premier = signe au premier & signe.
je pense qu'ils avaient une semblable réponse ici:
nous connaissons ces personnages"?v=" n'apparaissent jamais plus de, mais de " v " peut apparaître en quelque sorte dans l'Id lui-Même pour nous "?v=" comme délimiteur. Voir travailler ici
//Get YouTube video Id From Its Url
$('button').bind('click',function(){
var
url='http://www.youtube.com/watch?v=u8nQa1cJyX8',
videoId = url.split('?v='),//Split data to two
YouTubeVideoId=videoId[1];
alert(YouTubeVideoId);return false;
});
<button>Click ToGet VideoId</button>
regex Simple si vous avez L'URL complète, gardez-le simple.
results = url.match("v=([a-zA-Z0-9]+)&?")
videoId = results[1] // watch you need.
var video_url = document.getElementById('youtubediv').value;
if(video_url!=""){
ytid(video_url);
document.getElementById("youtube").setAttribute("src","http://www.youtube.com/embed/"+ytid(video_url));
}
function ytid(video_url){
var video_id = video_url.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}
return video_id;
}
j'espère que cela peut aider à
function youtube_parser(url){
var match = url.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/);
return (match&&match[7].length==11)?match[7]:false;
}
le plus court et efficace
Comme webstrap mentionné dans un commentaire :
ça a marché si la vidéo commence avec" v " et qu'elle vient de youtu.be
le regex contient un petit bug
\??v?=?
cela devrait juste être à la regardez la pièce, sinon vous filtrerez un'v'
si l'id commence par un'v'
. donc, cela devrait faire l'affaire
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/
j'ai apporté de légères modifications au mantish's regex pour inclure tous les cas d'essai des réponses JW et matx's , car cela n'a pas fonctionné sur tous les cas au départ. D'autres changements pourraient être nécessaires, mais pour autant que je puisse dire cela couvre au moins la majorité des liens:
/(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/
var url = ''; // get it from somewhere
var youtubeRegExp = /(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/;
var match = url.match( youtubeRegExp );
if( match && match[ 1 ].length == 11 ) {
url = match[ 1 ];
} else {
// error
}
Pour poursuivre l'essai:
En C#, il ressemble à ceci:
public static string GetYouTubeId(string url) {
var regex = @"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|watch)\/|.*[?&]v=)|youtu\.be\/)([^""&?\/ ]{11})";
var match = Regex.Match(url, regex);
if (match.Success)
{
return match.Groups[1].Value;
}
return url;
}
n'hésitez pas à modifier.
j'ai fait une petite fonction pour extraire l'id de la vidéo à partir d'une url Youtube qui peut être vu ci-dessous.
var videoId = function(url) {
var match = url.match(/v=([0-9a-z_-]{1,20})/i);
return (match ? match['1'] : false);
};
console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'));
console.log(videoId('https://www.youtube.com/watch?t=17s&v=dQw4w9WgXcQ'));
console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=17s'));
cette fonction extraira l'id de la vidéo même s'il y a plusieurs paramètres dans l'url.
vous pouvez utiliser le code suivant pour obtenir L'ID de la vidéo YouTube à partir d'une URL:
url = "https://www.youtube.com/watch?v=qeMFqkcPYcg"
VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
alert(url.match(VID_REGEX)[1]);