Validate Youtube (plus Shorts) URL and extract ID

Incase anyone else needs to regex for validating YouTube URLS and extracting YouTube IDs from the same URLs.

[Mainly for my reference, as I forgot when I needed to do it again]

To check if they are valid - create a custom state - then on whatever condition you need to kick it off, say a button …

RegEx for this is: (includes the newer YouTube shorts)

^((?:https?:)?//)?((?:www|m).)?((?:youtube.com|youtu.be))(/(?:[\w-]+?v=|embed/|v/|shorts/)?)([\w-]+)(\S+)?$

Now after the check to see if its valid you can fire off the extraction which looks like this. And for illustration purposes this is then saving to a state for me to test but you could save to the DB or show it or whatever.

RegEx:(?<=watch?v=|/videos/|embed/|shorts/|youtu.be/|/v/|watch?v=|/videos/|embed/|youtu.be/|/v/)[^#&?\n]*

includes YT shorts as well.

Got some reminders from this thread How to extract YouTube IDs with Regex and getting poster images

I created a little validator reusable that I thought I would share as its a nice way to contain login you may want to use elsewhere.

Its very simple and contains what I have done above

With two custom states -

Drop it on the page where you have the input and trigger a workflow ‘custom event from a reusable’ and fill in the blanks

Then use the output states of the reusable to do whatever else you need.

1 Like