Menu
CoddyTech

Text Inside HTML

Part of the Express Basics section of Coddy's Node.js journey. Lesson 9 of 23.

A visitor can type characters that HTML treats as markup. If a title contains <b>, placing it directly in a page creates a tag. Escaping turns these characters into text the browser displays.

escapeHtml('<b>Lunch</b>');
// &lt;b&gt;Lunch&lt;/b&gt;

The helper turns & into &amp;, which the browser displays as an ampersand. Double quotes become &quot;; apostrophes stay unchanged. Escape every inserted text value, whoever wrote it, before surrounding it with your own HTML. Escaping the entire page would display your heading tags as text too. You do not need to write the helper; the important decision is where to use it.

In a URL, write a space as %20, an ampersand as %26, and angle brackets as %3C and %3E. These encodings keep title text separate from query syntax.

challenge icon

Challenge

Easy

Edit exercise.js. Use the supplied helper on the title before placing it inside your own heading tags. Return the completed heading in html.

Try Run: GET /result?title=Fish%20%26%20Chips returns {"html":"<h1>Fish &amp; Chips</h1>"}. Try /result?title=%3Cb%3ELunch%3C%2Fb%3E: the inserted title must be text, while your heading remains markup.

Try it yourself

import { escapeHtml } from './html.js';
export function exercise({ title }) {
    return { html: `<h1>${title}</h1>` };
}

All lessons in Express Basics

Practice on your own: Express playground