Gli ID dei video di YouTube rappresentano la parte più rilevante di un URL di un video di YouTube. La procedura per ottenerli non è complessa.
Possiamo implementare la seguente funzione di utility:
'use strict';
const getYouTubeVideoID = url => {
const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
const match = url.match( regExp );
if ( match && match[7].length == 11 ) {
return match[7];
} else {
return new Error( `${url} is not a valid YouTube URL` );
}
}
Esempio d'uso:
'use strict';
const ytURL = 'https://www.youtube.com/embed/coIsvOMYEi0?rel=0';
const ytVideoID = getYouTubeVideoID( ytURL ); // 'coIsvOMYEi0'