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

Introducing Component Adapters into a Gatsby Project

Component adapters are a great way to separate logic from presentation in component-driven development projects. Here's how I've implemented the approach in Gatsby.

Jul 17, 2020

ES6 Build Pipeline for Middleman using Gulp

Middleman has abandoned its asset pipeline in favor of a more flexible and customized approach. Let's use this new approach to get ES6 modules into our Middleman project.

Oct 16, 2018

Incrementing Variables in JavaScript

JavaScript has three different types of incrementers: i++ ++i and i+=1. Let's look at how they differ from one another.

Apr 06, 2021