Template literals with backticks let you drop values into a string with ${...}. A tagged template goes one step further: you put a function name in front of the backticks, and that function receives the text pieces and the values separately. It can then escape, format or check each value before joining everything together, or even return something that is not a string at all. Libraries use this for safe HTML, database queries, translations and CSS.
In this lesson you will learn
- How a tag function receives
stringsandvalues - Rebuilding the string with your own rules
- Formatting numbers as money inside templates
strings.rawandString.raw- Safer HTML and SQL with tags
You should know strings and template literals and reduce.
How Tags Work
// A tag is a function placed right before a template literal
function inspect(strings, ...values) {
console.log("strings:", strings);
console.log("values: ", values);
return "done";
}
const item = "mango", qty = 3;
inspect`Buy ${qty} kg of ${item} today`;
// The tag decides what the final result is
function highlight(strings, ...values) {
return strings.reduce((out, str, i) =>
out + str + (i < values.length ? `[${values[i]}]` : ""), "");
}
console.log(highlight`Order ${42} for ${"Karim"} is ready`);
// Format every number in the template as Bangladeshi taka
const taka = new Intl.NumberFormat("en-IN");
function money(strings, ...values) {
return strings.reduce((out, str, i) => {
const v = values[i - 1];
return out + (typeof v === "number" ? "Tk " + taka.format(v) : v) + str;
});
}
const total = 1250000, paid = 75000;
console.log(money`Total ${total}, paid ${paid}, due ${total - paid}`);
// strings.raw keeps backslashes exactly as typed
function showRaw(strings) { return strings.raw[0]; }
console.log(showRaw`C:\new\table`);
console.log(String.raw`Line 1\nstill line 1`);
Output
strings: [ 'Buy ', ' kg of ', ' today' ]
values: [ 3, 'mango' ]
Order [42] for [Karim] is ready
Total Tk 12,50,000, paid Tk 75,000, due Tk 11,75,000
C:\new\table
Line 1\nstill line 1
- A tag is written as
name`text`, with no brackets. JavaScript calls the function for you. - The first argument,
strings, is an array of the fixed text pieces. The rest are the values from each${...}. - There is always one more string than there are values: the text before the first value, between each value and after the last. The pieces can be empty strings.
- The tag returns whatever it likes.
highlightwraps each value in square brackets, andmoneyformats numbers in the Bangladeshi style (12,50,000). reducewithout a starting value begins withstrings[0], then adds value and string pairs. It is a common, short way to rebuild the text.strings.rawholds the text exactly as typed, with backslashes kept. The built-inString.rawtag uses it, which is handy for Windows paths and regular expressions.
Safer HTML and SQL
// Safe HTML: escape every inserted value, but keep the template's own tags
const escapeHTML = s => String(s)
.replace(/&/g, "&").replace(/</g, "<")
.replace(/>/g, ">").replace(/"/g, """);
function html(strings, ...values) {
return strings.reduce((out, str, i) => out + escapeHTML(values[i - 1]) + str);
}
const comment = '<img src=x onerror="alert(1)">Nice post!';
console.log(html`<p class="comment">${comment}</p>`);
// A tiny query builder that keeps values apart from the SQL text
function sql(strings, ...values) {
return {
text: strings.reduce((out, str, i) => out + "$" + i + str),
values
};
}
const city = "Khulna", minAge = 18;
const query = sql`SELECT * FROM students WHERE city = ${city} AND age >= ${minAge}`;
console.log(query.text);
console.log(query.values);
// Tags can also return non-strings, such as a reusable function
function template(strings, ...keys) {
return data => strings.reduce((out, str, i) => out + data[keys[i - 1]] + str);
}
const receipt = template`Dear ${"name"}, your ${"plan"} plan renews on ${"date"}.`;
console.log(receipt({ name: "Tanvir", plan: "Student", date: "1 Jan 2027" }));
console.log(receipt({ name: "Lima", plan: "Family", date: "15 Feb 2027" }));
Output
<p class="comment"><img src=x onerror="alert(1)">Nice post!</p>
SELECT * FROM students WHERE city = $1 AND age >= $2
[ 'Khulna', 18 ]
Dear Tanvir, your Student plan renews on 1 Jan 2027.
Dear Lima, your Family plan renews on 15 Feb 2027.
- The
htmltag escapes every inserted value, but not the template’s own tags. A comment containing<img onerror=...>becomes harmless text instead of running code. This blocks a common attack called cross-site scripting (XSS). - The
sqltag never pastes values into the SQL text. It writes placeholders ($1,$2) and returns the values separately. A database driver then sends them apart, which prevents SQL injection. - Tags can return any type.
templatereturns a function, so one template can be filled in many times with different data.
| Where you will see tags | Example |
|---|---|
| Raw strings | String.raw`C:\temp` |
| HTML templates (lit) | html`<p>${text}</p>` |
| CSS-in-JS (styled-components) | styled.button`color: red;` |
| Database queries | sql`SELECT * FROM t WHERE id = ${id}` |
| GraphQL | gql`{ user { name } }` |
Common Mistakes
- Calling the tag with brackets, such as
html(`...`). That passes one finished string, so the tag cannot see the values separately. - Forgetting the last string piece when joining, which drops the text after the final value.
- Escaping the template’s own HTML instead of only the values, which shows tags as text.
- Building SQL by pasting values into the text. Always keep values separate and let the database driver handle them.
Practice Exercises
Exercise 1. Write an upper tag that turns every inserted value into uppercase but leaves the fixed text alone.
Show answer
const upper = (strings, ...values) =>
strings.reduce((out, str, i) => out + String(values[i - 1]).toUpperCase() + str);
const name = "rafi";
console.log(upper`Welcome, ${name}!`); // "Welcome, RAFI!"
Exercise 2. Write a count tag that returns the number of values in a template.
Show answer
const count = (strings, ...values) => values.length;
console.log(count`${1} and ${2} and ${3}`); // 3
Frequently Asked Questions
Is the strings array the same object every time?
Yes. For one particular tagged template in your code, JavaScript passes the same frozen strings array on every call. Libraries use this to cache work, such as parsing an HTML template only once.
Does a tag make my HTML completely safe?
It escapes text values, which stops most attacks. Values placed inside URLs, such as href, still need extra checks, because a link like javascript: contains no characters that need escaping.
Summary
- A tag function receives the fixed text pieces and the inserted values separately.
- It can format, escape or check values, and may return any type.
String.rawkeeps backslashes as typed.- Tags make HTML and SQL safer by treating values differently from the template text.
