← All Exercises

Extract Allowlisted Links from HTML

basicjavascript~25min

Background

Scrapers that follow every link wander off-site and duplicate work. Host allowlisting is the simplest boundary that keeps a crawl focused.

Problem

Extract anchor hrefs and their visible text from an HTML fragment, keep only allowlisted hosts, and report how many links were skipped.

Input

JSON object: { html: string, allowedHosts: string[] }

Output

JSON object: { links: [{ href, text }], skipped: number }

Sample tests

Sample 1

Input: {"html":"<a href=\"https://docs.example.com/start\">Start</a><a href=\"https://ads.other.com/x\">Ad</a>","allowedHosts":["docs.example.com"]}
Expected: {"links":[{"href":"https://docs.example.com/start","text":"Start"}],"skipped":1}

Sample 2

Input: {"html":"<a href=\"https://docs.example.com/a\"><b>Bold</b> label</a>","allowedHosts":["docs.example.com"]}
Expected: {"links":[{"href":"https://docs.example.com/a","text":"Bold label"}],"skipped":0}

Your solution

Learning objective

Keep a crawler inside its allowed hosts while preserving link text.