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

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])
}

Leave a Reply