Home

Extract GitHub Repo Name from URL using JavaScript

Quick JavaScript/Node snippet that can pul a GitHub repo path from a full GitHub URL.

Here’s a handy function that will extract the repo path from a valid GitHub URL:

export function extractGitHubRepoPath(url) {
if (!url) return null;
const match = url.match(
/^https?:\/\/(www\.)?github.com\/(?<owner>[\w.-]+)\/(?<name>[\w.-]+)/
);
if (!match || !(match.groups?.owner && match.groups?.name)) return null;
return `${match.groups.owner}/${match.groups.name}`;
}

Here we’re using a named capture group to independently retrieve the owner and name of a particular repo. We can then more easily ensure we have both, and return null if not.

It accounts for the following conditions:

  • A falsey value for url (returns null)
  • Using an insecure URL (http and not https)
  • Including or omitting www subdomain (works with github.com and www.github.com)
  • Any number of URL fragments following the repo path — e.g. https://github.com/seancdavis/seancdavis-com/blob/main/www/src/pages/index.md would return seancdavis/seancdavis-com
  • Invalid URLs — anything that doesn't match the pattern, including having an owner and name match, returns null

Let's Connect

Keep Reading

Manipulate iFrame Content

When you can communicate with the code inside an iFrame, you can make any change you want to the code within that iFrame.

May 02, 2018

Dynamically Changing a Netlify Form Name

Netlify forms are easy to use because they are simple in scope. Add a little power with this cool trick.

Mar 31, 2021

Should You Learn jQuery in 2022?

It may seem like jQuery has been dead for years, but it is still widely used in 2022. But should you take the time to learn it?

Jul 22, 2022