Skip to content
Lesson 6 of 20

Step 1 of 5 · Reading · ~3 min

Read

Inline Elements

Links and Images

[text](url)                ->  <a href="url">text</a>
[text](url "a title")      ->  <a href="url" title="a title">text</a>
![alt](url)                ->  <img src="url" alt="alt" />
<https://example.com>      ->  an autolink

An image is a link with an exclamation mark in front of it. That one character is the whole difference in the syntax — and it is also the source of the single most common bug in hand-written Markdown parsers.

Why must images be substituted before links?

Because the link pattern happily matches the inside of an image. Run the two substitutions in the wrong order and the ! is left stranded outside an anchor:

python

Line one is the bug. Line three is the next one waiting for you: [^)]+ stops at the first closing paren, so a URL that legitimately contains parentheses gets truncated and the leftover ) leaks into the text. CommonMark allows balanced parens inside a bare destination, and lets you sidestep the whole question by wrapping the destination in angle brackets — [wiki](<https://example.com/a_(b)>).

The four bracket shapes

FormLooks likeResolves how
Inline[text](url)URL is right there
Reference[text][label]looked up in a table built earlier
Collapsed[label][]label doubles as the text
Autolink<https://example.com>the URL is also the text (an email autolink adds mailto: to the href)

Only the first is in scope for this exercise; the reference forms get their own lesson, because they force the parser to resolve names that may be defined further down the document.

What is different about an image?

The alt attribute is plain text, always. If the label contains markup — ![a *nice* logo](x.png) — the emphasis is flattened, and the alt value ends up as a nice logo. An <img> attribute cannot hold an <em> element, so the renderer walks the label and keeps only the characters.

The other rule worth remembering: links do not nest. A link label may contain emphasis, code, or an image, but never another link. Bracket-matching inside a link label stops at the first unescaped ], which is exactly what [^\]]+ gives you for free.

Your exercise

Convert inline links and images on every line, and pass other lines through.

The mistake the grader catches is ordering. A hidden test feeds Mixed: [text](url1) plain ![alt](url2) more, and if links run first that line comes back with !<a href="url2">alt</a> where an <img> belongs. Substitute the image pattern first, then the link pattern, on the already-transformed string.

Watch the exact output shape too: the tests want <img src="url" alt="alt" /> with a space before the self-closing slash, and <a href="url">text</a> with no title attribute at all. An extra title="" or a missing space is a diff.

Up nextAutolinksInline Elements

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…