Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
18.4. Extract the links from an HTML string
Medium
Topics
This question is in
18. URLs, storage and safe HTMLA link checker, a "links in this article" sidebar, a crawler and an email preview all need the same thing: every link in a piece of HTML, with an absolute address. Regular expressions look tempting and fail on real markup: links inside comments or scripts, attributes without quotes, & in an address, tags the author forgot to close. The browser already has a parser that handles all of it.
Write extractLinks(html, baseUrl) in extract-links.js.
Signature
function extractLinks(html, baseUrl) // returns [{ href, text }, …]html: a string of HTML, a fragment or a whole document, possibly untrusted.baseUrl: the absolute URL the HTML came from; relative addresses resolve against it.- Returns plain objects
{ href, text }in document order.
Requirements
- Each
<a>element with anhrefattribute becomes{ href, text };<a>withouthrefis skipped. hrefis the attribute resolved againstbaseUrlas an absolute URL string (asnew URL(…).hrefwrites it). An emptyhrefis the base URL itself.- Only
http:andhttps:links are kept:javascript:,mailto:,tel:,data:,ftp:and the rest are skipped, however they are written (case, spaces, tabs, character references). - An
hrefthat is not a valid URL is skipped; the function does not throw for it. - Character references are decoded in both
hrefandtext(&is&). textis the link's whole text content, with every run of whitespace turned into one space and trimmed. A link with only an image has the text"".- Markup that is not really a link is ignored: links inside comments, inside
<script>,<style>,<textarea>or<title>, and inside attribute values. - Upper-case tags, single quotes and unquoted attributes work; unclosed and stray tags are repaired the way a browser repairs them.
- Duplicates are kept. No links gives
[]. - An invalid
baseUrlthrowsTypeError. - Parsing must run nothing: no script from the HTML runs and no image starts loading.
Examples
extractLinks('<p>Read <a href="/guide?x=1&y=2">the <b>guide</b></a></p>', "https://shop.example/blog/");
// [{ href: "https://shop.example/guide?x=1&y=2", text: "the guide" }]extractLinks('<a href="../about">About</a><a href="mailto:hi@shop.example">Mail</a>', "https://shop.example/blog/post");
// [{ href: "https://shop.example/about", text: "About" }]extractLinks('<!-- <a href="/old">old</a> --><a href=/new>new', "https://shop.example/");
// [{ href: "https://shop.example/new", text: "new" }]Environment
- Plain JavaScript in a browser page; the tests call the global
extractLinksfromextract-links.js. DOMParser,<template>andURLare all available. One test checks that anonerrorhandler in the HTML never runs.- Out of scope:
<area>and SVG links,<base>elements inside the HTML (resolve againstbaseUrl), and removing duplicates.
Hints
a.hrefanda.getAttribute("href")return different things. Which one knows aboutbaseUrl?- Which ways of turning a string into elements create a document where nothing loads?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…