Using Regex.exec with parentheses regex to extract matches of a string
suggest changeSometimes you don’t want to replace or remove the text. You want to extract matches and process them.
exec returns null or a match array. The first element is the whole match. Each following element is a capture group.
Imagine this HTML:
<html>
<head></head>
<body>
<h1>Example</h1>
<p>Look a this great link : <a href="https://stackoverflow.com">Stackoverflow</a> http://anotherlinkoutsideatag</p>
Copyright <a href="https://stackoverflow.com">Stackoverflow</a>
</body>
</html>
You want every link inside an a tag. One expression for the whole tag is:
const re = /<a[^>]*href="https?:\/\/.*"[^>]*>[^<]*<\/a>/g;
But now, imagine you want the href and the anchor of each link. And you want it together. You can simply add a new regex in for each match OR you can use parentheses :
const re = /<a[^>]*href="(https?:\/\/.*)"[^>]*>([^<]*)<\/a>/g;
const str = '<html>\n <head></head>\n <body>\n <h1>Example</h1>\n <p>Look a this great link : <a href="https://stackoverflow.com">Stackoverflow</a> http://anotherlinkoutsideatag</p>\n\n Copyright <a href="https://stackoverflow.com">Stackoverflow</a>\n </body>\n';
let m;
const links = [];
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
console.log(m[0]); // The whole match
console.log(m[1]); // The href subpart
console.log(m[2]); // The anchor subpart
links.push({
match : m[0], // the entire match
href : m[1], // the first parenthesis => (https?:\/\/.*)
anchor : m[2], // the second one => ([^<]*)
});
}
The .* in the href group is greedy, and . does not cross a newline here, so each match stays on one line. After the loop, links has the anchor and href of each match:
links.forEach(function(link) {
console.log('[%s](%s)', link.anchor, link.href);
});
To go further :
- Nested parenthesis
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents