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

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

WTF is Lodash?

Explore an introduction to Lodash and what it can do to support your JavaScript code.

Apr 21, 2020

WTF is deep-for-each?

Explore an introduction to the super cool, single-function JavaScript package, deep-for-each.

Apr 16, 2020