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

WTF is Jest?

Learn the basics of the JavaScript testing framework, Jest.

Aug 23, 2021

Compile ES6 Code with Gulp and Babel, Part 3

In the third of five parts on compiling multiple ES6 files into a minified bundle, you will learn how to use a configuration file to build multiple dynamic manifest bundles.

Dec 19, 2018

Run JavaScript Script Before Another Script

Automatically run scripts with NPM/Yarn before or after another script.

May 09, 2022