Extracting YouTube Video IDs from URLs
In this quick Bubble tutorial, I'm going to show you how to extract a YouTube video's ID from a YouTube URL. This can be useful if you're embedding YouTube videos, depending on how you store that data in your database.
Using Find and Replace
One way to go about this is to use the find and replace function. I'm going to say input input a to refer to my input field value and then use find and replace. This is such a handy trick where you can find some text in a string in the input field and replace it with nothing.
Handling Different URL Formats
We have to cover many different eventualities as we can't always rely on our users inputting data in the same format. For example, what happens if they use the share URL, which is YouTube's link shortener? Let's copy that into here, and you'll see that it doesn't work. But what we can do is stack our find and replaces.
Dealing with Query Strings
There is another eventuality to cover, and that is if the URL has got some sort of query string at the end. For example, if we jump midway through the video and then say start from now, this is a query string related to time. But there could be other things to do with tracking and the source where people have arrived at the website from.
Using Truncate for Consistency
There's one final thing that I'd add, which is to truncate. Truncate means to trim our text, and YouTube video IDs are all 11 characters long. There's a really fascinating video by Tom Scott which we can link to, saying how YouTube is really unlikely to run out of video IDs - the math on it is astonishing.
Putting It All Together
We can say truncate to 11, so now if I paste in with the query string, it still only sticks to the first 11 characters of what's remained after we've done the find and replace. Let's just check this with our full URL. I'll add a query string here, and it still works because it removes everything in front of it, leaving only what's after this part of the URL. Then we can use truncate to limit what we return to just 11 characters.
Conclusion
This method allows us to extract YouTube video IDs consistently, regardless of the URL format or additional parameters. It's a useful technique when working with YouTube videos in your Bubble app.