convertUrlToId static method
Converts fully qualified YouTube Url to video id.
If videoId is passed as url then no conversion is done.
Implementation
static String? convertUrlToId(String url, {bool trimWhitespaces = true}) {
if (!url.contains("http") && (url.length == 11)) return url;
if (trimWhitespaces) url = url.trim();
const contentUrlPattern = r'^https:\/\/(?:www\.|m\.)?youtube\.com\/watch\?';
const embedUrlPattern =
r'^https:\/\/(?:www\.|m\.)?youtube(?:-nocookie)?\.com\/embed\/';
const altUrlPattern = r'^https:\/\/youtu\.be\/';
const shortsUrlPattern = r'^https:\/\/(?:www\.|m\.)?youtube\.com\/shorts\/';
const musicUrlPattern = r'^https:\/\/(?:music\.)?youtube\.com\/watch\?';
const idPattern = r'([_\-a-zA-Z0-9]{11}).*$';
for (var regex in [
'${contentUrlPattern}v=$idPattern',
'$embedUrlPattern$idPattern',
'$altUrlPattern$idPattern',
'$shortsUrlPattern$idPattern',
'$musicUrlPattern?v=$idPattern',
]) {
Match? match = RegExp(regex).firstMatch(url);
if (match != null && match.groupCount >= 1) return match.group(1);
}
return null;
}