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:
url
(returns null
)http
and not https
)www
subdomain (works with github.com
and www.github.com
)https://github.com/seancdavis/seancdavis-com/blob/main/www/src/pages/index.md
would return seancdavis/seancdavis-com
owner
and name
match, returns null