Browsers turn raw HTML text into structures the page can work with. Building a tiny slice of that logic is a practical way to learn how HTML parsing works: you have to walk the string, recognize where tags begin and end, and avoid being tricked by characters like > when they appear inside quoted attributes.
In this interview-sized version, implement extractAnchors(html), which returns every complete anchor element from an HTML string in source order.
Each returned item should be the exact substring from the original input, including attributes, whitespace, and nested non-anchor markup inside the anchor.
extractAnchors('<div> <a href="/home" >Home</a > <span>Later</span> <a >Docs</a> </div>',);// ['<a href="/home" >Home</a >', '<a >Docs</a>']
extractAnchors(`<section><p>Read <ahref="https://example.com/docs"data-track="docs link">the docs</a> first.</p></section>`,);// [// `<a// href="https://example.com/docs"// data-track="docs link"// >the docs</a>`// ]
extractAnchors(`<div><a href="https://example.com/guides" class="link" ><abbr>API</abbr><span>guide</span></a></div>`,);// [// `<a href="https://example.com/guides" class="link" >// <abbr>API</abbr>// <span>guide</span>// </a>`// ]
extractAnchors(html)
html (string): A valid HTML-like string.Returns an array of anchor element substrings in source order.
<a ...> and </a> tags need to be handled.DOMParser, innerHTML, querySelectorAll(), getElementsByTagName(), or similar DOM helpers.console.log() statements will appear here.