Skip to content

Instantly share code, notes, and snippets.

@cds-amal
Created June 1, 2021 15:32
Show Gist options
  • Save cds-amal/a66ec1079d9d34c12669bb8e0a2b7aba to your computer and use it in GitHub Desktop.
Save cds-amal/a66ec1079d9d34c12669bb8e0a2b7aba to your computer and use it in GitHub Desktop.
/* Named capture groups (ECMAScript regex flavour)
*/
const rex = new RegExp(
"(?<protocol>https://)" + // capture group https://
"(?<gitService>[^:/]+)" + // anything not a : or /
"/" +
"(?<orgName>[^/]+)" + // capture org name
"/" +
"(?<repo>[^#]+)" + // capture repo
"#?" + // optional branch separator
"(?<branch>.+)?", /* optionally capture branch
* if it doesn't match branch will be undefined
*/
"i" // case insensitive
);
const urls = [
"https://github.com/truffle-box/metacoin-box#fix/one",
"https://github.com/truffle-box/metacoin-box"
];
for (const url of urls) {
console.log(`\nURL: ${url}`);
const match = url.match(rex);
const { groups: G } = match;
console.log(G);
const optionalBranch = G['branch'] ? `#${G['branch']}` : '';
console.log(`Normy Url: ${G['protocol']}${G['gitService']}:${G['orgName']}/${G['repo']}${optionalBranch}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment