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

Reload Page with Javascript

Reloading a page on the fly is easy with JavaScript.

Jan 04, 2015

Better Website Performance with Pixelated Placeholder Images

Page load times decrease as the number of images on a page increase. Learn the pixelated placeholder method that mitigates performance issues caused by images without negatively impacting user experience.

Jan 09, 2019

2 Methods for Binding JavaScript Events with 11ty

When using raw JavaScript with 11ty, there are multiple approaches you can take for binding events, all without complicating the JavaScript you’re using.

Sep 29, 2022