nishanthg92
Validating youtube link
How to validate different kind of a youtube link?
for example:
http://youtu.be/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://www.youtube.com/?v=dQw4w9WgXckQ
and convert this link to embed link like http://www.youtube.com/embed/dQw4w9WgXcQ to embed video in our application?
First Post!
wmnnd
YouTube links can easily be matched with regular expressions.
Check out this introduction to regular expressions if you’re not familiar with them yet:
If you want to learn how to use regular expressions in Elixir, take a look at the documentation of the Regex module which has a nice introduction to using them and detailed information about the individual methods:
Most Liked
NobbZ
If the video IDs are guaranteed to be at the end, you can do a pattern match, which is probably a lot faster:
def get_video_id("http://youtu.be/" <> id), do: id
def get_video_id("http://www.youtube.com/watch?v=" <> id), do: id
def get_video_id("http://www.youtube.com/?v=" <> id), do: id
How you can append that video ID to the string "http://www.youtube.com/embed/" is left as an exercise.
I’d prefer to make it HTTPS ready and solve it via meta programming, roughly like this:
Enum.each(["http", "https"], fn protocol ->
Enum.each(["youtu.be/", "www.youtube.com/watch?v=", "www.youtube.com/?v="], fn prefix ->
def get_video_id(unquote(protocol <> "://" <> prefix) <> id), do: id
end)
end)
But probably the best version is to properly parse the URL and extract the video ID from the parsed URL. Pattern matching as shown by me will not work correctly when there are other parameters in the query string, and regular expressions that cover those possibilities tend to grow into an unreadable and slow monstrosity.
Last Post!
nishanthg92
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









