Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex YouTube channel link

I’m looking for a Javascript regex which is able to extract the channel identifier of a YouTube channel link. I’ve found some solutions on Stackoverflow but I’m still missing a solution which is also capable to work with the YouTube channel alias (e.g. https://www.youtube.com/@youtubecreators)

So the regex should be able to match following URLs:

  1. https://www.youtube.com/c/coca-cola –> coca-cola
  2. https://www.youtube.com/channel/UCosXctaTYxN4YPIvI5Fpcrw –> UCosXctaTYxN4YPIvI5Fpcrw
  3. https://www.youtube.com/@coca-cola –> coca-cola
  4. https://www.youtube.com/coca-cola –> coca-cola

The matching should also work even when there’s a path attached like https://www.youtube.com/@Coca-Cola/about

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any hints are welomce!

>Solution :

The pattern you’re looking for is:

https:\/\/www\.youtube\.com\/(?:c\/|channel\/|@)?([^/]+)(?:\/.*)?
const urls = [
  "https://www.youtube.com/c/coca-cola",
  "https://www.youtube.com/channel/UCosXctaTYxN4YPIvI5Fpcrw",
  "https://www.youtube.com/@coca-cola",
  "https://www.youtube.com/coca-cola",
  "https://www.youtube.com/@Coca-Cola/about",
]

const pattern = /https:\/\/www\.youtube\.com\/(?:c\/|channel\/|@)?([^/]+)(?:\/.*)?/

for (url of urls) {
  console.log(url.match(pattern)[1])
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading