function getYoutubeIdAndTimestamp(url: string) {
if (!url) {
return { videoId: null, startTime: 0 };
}
// Regular expression to extract YouTube video ID
const idPattern = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|(?:m\.)?youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
const idMatch = url.match(idPattern);
const videoId = idMatch ? idMatch[1] : null;
if (!videoId) {
return { videoId: null, startTime: 0 };
}
// Regular expression to check for timestamp (t=209, t=209s, start=209, start=209s)
const timePattern = /[?&](?:t|start)=(\d+)s?/;
const timeMatch = url.match(timePattern);
const startTime = timeMatch ? parseInt(timeMatch[1], 10) : 0;
return { videoId, startTime };
}
// Example usage
console.log(getYoutubeIdAndTimestamp("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=209s")); // { videoId: "dQw4w9WgXcQ", startTime: 209 }
console.log(getYoutubeIdAndTimestamp("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=209")); // { videoId: "dQw4w9WgXcQ", startTime: 209 }
console.log(getYoutubeIdAndTimestamp("https://www.youtube.com/watch?v=dQw4w9WgXcQ&start=209s")); // { videoId: "dQw4w9WgXcQ", startTime: 209 }
console.log(getYoutubeIdAndTimestamp("https://www.youtube.com/watch?v=dQw4w9WgXcQ&start=209")); // { videoId: "dQw4w9WgXcQ", startTime: 209 }
console.log(getYoutubeIdAndTimestamp("https://youtu.be/dQw4w9WgXcQ")); // { videoId: "dQw4w9WgXcQ", startTime: 0 }
Last active
March 12, 2025 08:47
-
-
Save manzil-infinity180/76deeb86d129fdba887bbd7645095f13 to your computer and use it in GitHub Desktop.
Youtube Video Id and get the specified time
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment