Home > Back-end >  Regex YouTube channel link
Regex YouTube channel link

Time:02-06

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!

CodePudding user response:

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

CodePudding user response:

try this

/^https?:\/\/(www\.)?(youtube\.com\/(@[a-zA-Z0-9-] |c\/[a-zA-Z0-9-] |channel\/[a-zA-Z0-9-] )|youtube\.com\/[a-zA-Z0-9-] )/

Code Example:

const url = 'https://www.youtube.com/@coca-cola/about';
const channelIdentifier = url.match(/^https?:\/\/(www\.)?(youtube\.com\/(@[a-zA-Z0-9-] |c\/[a-zA-Z0-9-] |channel\/[a-zA-Z0-9-] )|youtube\.com\/[a-zA-Z0-9-] )/)[3].replace(/^@|^c\/|^channel\//, '');
console.log(channelIdentifier); // outputs 'coca-cola'
  • Related