const regex = /<a[^>]*?href=(?|"([^"]*?)"|'([^']*?)').*?>(.*?)<\/a>/gsi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('<a[^>]*?href=(?|"([^"]*?)"|\'([^\']*?)\').*?>(.*?)<\\\/a>', 'gsi')
const str = `# Basic Cases
<a href="http://test.com">double quotes</a>
<a href='http://test.com'>single quotes</a>
<a class="blah a href" data="blah" href="#rel-link" rel=''>complicated attributes</a>
<a href="#anchor-1">adjacent</a><a href="#anchor-2">anchors</a>
# Extra Cases
<a href="http://test.com">title
linebreak</a>
<a href="#anchor-reference"><span>inline span</span></a>
<ahref="uri:test-uri">technically invalid anchor</a>
<a href="http://test.com"><a href="#invalid">technically invalid internal anchor</a></a>
<a href="'''''\\"\\"">quotes test</a>
# Random Junk Stress Tests
<a class="" href=""rergerger er erg><></><>.e.ewfe></wef/we. ></a>Test</a>
<ahref="e">e</a>
<a>e</a>
<a href="">e<a href="">e</a></a>
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions