Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.7 — Tagged Templates and String.raw
JavaScript · Example 2 of 3 ES2015+

An html tag that escapes values

The developer's markup stays markup; the user's text is shown as text. This is the core idea behind lit-html. For plain text, textContent is even simpler (Topic 8.3).

Putting a function name right before a template literal, as in tagHi ${name}, calls that function with the literal's fixed text parts and its values separately, so it can escape, format or reshape them before building the result; String.raw is the built-in tag that keeps backslashes as written.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a tag highlight that wraps every substitution value in <mark> and </mark> (escaping is not needed for this task). Log ` highlightFound ${3} results for ${"tea"} `.

02

Use String.raw to build a regex that matches a Windows path starting with C:\Users\, and test it on C:\Users\asha.

Explain it without notes

01

What arguments does a tag function receive? How many strings and values are there?

02

What is the difference between strings[i] and strings.raw[i], and what does String.raw do?

03

How can a tagged template help prevent XSS or SQL injection?

An html tag that escapes values ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

<p class="comment"><strong>Asha</strong> says: &lt;b&gt;Hi&lt;/b&gt; &amp; &lt;i&gt;bye&lt;/i&gt;</p>
tags made from the user's text: 0
our own tags still work: 1