T5 Modern JavaScript (ES6 and later) · Lesson 2
Template literals in depth
Writing text that people read: what a gap turns its value into, text over many lines and the spaces that come with it, numbers in Indian groups and rupees with toLocaleString and Intl.NumberFormat, straight columns with padStart and padEnd, tagged templates and String.raw, and building HTML that a name cannot break.
- say what a template literal's gap turns each kind of value into
- write text over many lines without stray spaces and line breaks
- format numbers in Indian groups, as rupees and as percentages, with toLocaleString and Intl.NumberFormat
- line text up in columns with padStart and padEnd
- write a tagged template, and read a path with String.raw
- build HTML from text safely, escaping what a person typed
The back cover
Most of what a program shows people is text: a bill, a receipt, a table of marks, a page of results. Template literals, written in backticks, build that text with values set into gaps, and they can do far more than join words.
These pages show what a gap turns a value into, and how text spreads over many lines. They show numbers in Indian groups and in rupees, and text in straight columns. They show tagged templates, which hand the pieces to a function, and how to build HTML that a person's name cannot break.
Before you start
The story: A receipt nobody could read
On the upper floor, an old receipt printer serves the canteen downstairs. Its slips are honest but hard to read: Total 125000, with no commas, so that the cashier counts the zeros with a fingernail. The prices wander across the slip, one under the item, the next far out to the right.
This morning a customer who had written his name as <Ravi> got a slip with a blank where his name should be.
Master Hakim Verge holds the slip up to the window. "Every word on it is right," he says, "and the slip is still wrong. A receipt is for reading. Make the printer write numbers the way the city reads them, and names exactly as they were given."
The values lesson of the JavaScript step met template literals: text in backticks, with gaps that fill themselves. That is enough for a greeting. Real programs write receipts, reports, messages and pages, and for those the details matter. How is a number grouped? Does a column stand straight? Where did a stray space come from? And what does a name with an angle bracket in it do to a page? This lesson is about those details.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Template literals. | `Hi ${name}` | Every section. |
| Expressions in a gap. | `${3 * 80}` | A ternary, a call, even another template. |
| Escape sequences. | \n and \\ | String.raw keeps backslashes as written. |
| toFixed. | (3.3).toFixed(2) gives 3.30. | toLocaleString groups the digits too. |
| Indian digit groups. | 1,25,000 for one lakh twenty-five thousand. | The en-IN locale writes them. |
| padStart. | "7".padStart(4, "0") | With padEnd, for straight columns. |
| Functions and arguments. | tag(strings, values) | A tagged template calls a function. |
| innerHTML and XSS. | A user's tags become elements. | Escaping text before it goes into HTML. |
| replaceAll. | "a-b".replaceAll("-", "+") | Escaping, one character at a time. |
| JSON.stringify. | Shows a string's hidden characters. | Finding stray spaces and line breaks. |
By the end of this lesson you will be able to:
- say what a template literal's gap turns each kind of value into;
- write text over many lines without stray spaces and line breaks;
- format numbers in Indian groups, as rupees and as percentages, with
toLocaleStringandIntl.NumberFormat; - line text up in columns with
padStartandpadEnd; - write a tagged template, and read a path with
String.raw; - build HTML from text safely, escaping what a person typed.
How to follow this lesson
Every block on this page runs. When text comes out with a surprise in it, print it with JSON.stringify(text): it shows every hidden space and line break as \n inside quotes.
In one line
Template literals write the text people read; this lesson is about getting every number, space and character of it right.
What a gap turns a value into
At a glance
A form letter has blanks to fill: a name, a fee, a date. Whatever is written in a blank becomes part of the letter's words. A gap in a template literal is that blank, and whatever goes in it becomes text.
A gap turns its value into text as String(value) would. An array joins its items with commas, an object says [object Object], and null and undefined print as the words null and undefined. So choose the text yourself, with join, ?? or a property, and keep a long expression in a const above the template.
Take a guess: Why does an object in a gap print [object Object], and where does that text come from?
A gap in a template literal, ${...}, works out its expression and then turns the answer into text. For numbers and strings that is what you expect. For other values, the text is decided by rules worth knowing, because a wrong one shows up on a customer's screen.
console.log(`${[1, 2, 3]}`, `${{ a: 1 }}`, `${null} ${undefined}`, `${() => 1}`);
1,2,3 [object Object] null undefined () => 1
| In the gap | Becomes | Usually wanted instead |
|---|---|---|
| an array | its items with commas: 1,2,3 | list.join(", ") |
| an object | [object Object] | its properties, or JSON.stringify(obj) |
| null or undefined | the words null or undefined | a default, with ?? |
| a function | the function's own code | a call: ${f()} |
The rule behind the table is the same one the values lesson met: a gap uses the value's own way of turning into a string, as String(value) would. Arrays join their items, plain objects all say [object Object], and functions show their source. Choose the text yourself whenever the value is not a number or a string.
A gap is an expression
Anything that gives a value can go in a gap: arithmetic, a call, a ternary, even another template literal, which is called nesting:
const ok = false;
console.log(`Status: ${ok ? "paid" : `due by ${"Friday"}`}`);
Status: due by Friday
Nesting works, but a long gap is hard to read. When a gap needs more than a short expression, work the value out in a const on the line above, and put only the name in the gap.
A common mistake
Forgetting that the parts are joined as text. `${1 + 1}${"2"}` is the text 22, not the number 4: the first gap is worked out to 2, the second is the text 2, and the template joins them, as + joins strings.
console.log(`${1 + 1}${"2"}`, typeof `${1}`);
22 string
Worked example 1
A shop's order screen must show Items: tea, dal, oil, and a note that is the word none when there is no note. The items are an array, and the note is null.
What we have: an array of items, and a note that is null
What we need: the line Items: tea, dal, oil. Note: none
The plan: join the array with a comma and a space, and give the note a default with ??
const items = ["tea", "dal", "oil"];
const note = null;
console.log(`Items: ${items.join(", ")}. Note: ${note ?? "none"}`);
Items: tea, dal, oil. Note: none
It shows Items: tea, dal, oil. Note: none.
Check: without join the items would read tea,dal,oil, and without ?? the note would read null.
A path that fails: putting the array and the note in the gaps as they are. The screen then reads Items: tea,dal,oil. Note: null, which a customer may take for a note that says null.
When you are stuck: a gap shows something strange
[object Object] means an object went into the gap: pick its properties, or use JSON.stringify.
Commas with no spaces mean an array: use join with the separator you want.
null or undefined means a missing value: give a default with ??.
Code in the output means a function went in without brackets: call it.
Your turn
const user = { name: "Asha" };
console.log(`Hi ${user}`, `Hi ${user.name}`);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Hi [object Object] Hi Asha
- The whole object in a gap becomes [object Object].
- Its name property is a string: Asha.
It prints Hi [object Object] Hi Asha.
What does `${[4, 5]}` give?Tap to reveal
- An array in a gap joins its items with commas, no spaces.
The text 4,5.
How do you show the word none when note is null or undefined?Tap to reveal
- ?? gives its right side when the left is null or undefined.
`${note ?? "none"}`
Did you know?
Where [object Object] comes from
The odd text [object Object] is built by a rule. When an object with no toString of its own becomes text, the standard's Object.prototype.toString joins the word object, the object's tag and square brackets. MDN explains that the tag is looked up with Symbol.toStringTag, so built-in kinds name themselves: a Map in a gap prints [object Map].
Why it fits here: It explains this topic's [object Object]: the words are a label built from the object's tag, never its contents.
Sources: ECMAScript Language Specification: Object.prototype.toString; MDN: Symbol.toStringTag
A null that vanishes
A gap and join disagree about null. In a template literal, null prints as the word null. But MDN notes that join turns an undefined or null element into an empty string instead of the words. An array's toString calls join, so an array in a gap shows empty places where its nulls were: [1, null, 3] prints as 1,,3.
Why it fits here: It warns about this topic's arrays in gaps: null prints as null on its own, but as nothing inside an array.
Sources: MDN: Array.prototype.join(); MDN: Array.prototype.toString(); ECMAScript Language Specification: Object.prototype.toString
In one line
A gap turns its value into text as String(value) would: arrays join with commas, objects say [object Object], null and undefined print as words. Choose the text yourself, with join, ?? or a property, and keep long gaps in a const above.
Text over many lines
At a glance
A poem keeps its line breaks, and so does a template literal. Press Enter inside the backticks, and the line break becomes part of the text, with every space that follows it.
That includes the indentation of the code around it, which is a common surprise in printed text. Every space counts, even ones nobody can see. Start the text right after the backtick, or join an array of lines with \n. To see what is hidden, print the text with JSON.stringify, which shows each line break as \n.
Take a guess: Can the same template literal give different line breaks on different computers?
A template literal keeps everything between its backticks exactly as typed: every line break, every space. That is its strength for text over many lines, and its trap, because code is indented and the text inherits the indentation.
const slip = `Name: Asha
Seat: 42`;
console.log(slip);
Name: Asha
Seat: 42
Now the same text written the way code is usually laid out, starting on its own line and indented. Printed with JSON.stringify, which shows a line break as \n inside the quotes, the hidden characters appear:
const lines = `
Name: Asha
Seat: 42
`;
console.log(JSON.stringify(lines));
"\n Name: Asha\n Seat: 42\n"
The text starts with a line break, every line starts with two spaces, and it ends with another line break. On a screen that is a blank line and an indent nobody wanted; in a comparison, lines === "Name: Asha" is false for no visible reason.
Three ways to keep it clean
- Start the text right after the opening backtick, and write the following lines from the left edge, as the first block does.
- Build the lines as an array and join them:
["Name: Asha", "Seat: 42"].join("\n"). - For a single line that is only long, keep it on one line, or join shorter pieces with +.
const slip = ["Name: Asha", "Seat: 42"].join("\n");
console.log(JSON.stringify(slip));
"Name: Asha\nSeat: 42"
Each line break and tab inside a string, however written, is one character. A line break written as \n and one typed in a template are the same character:
console.log(`a
b`.split("\n").length, `tab\there`.length);
2 8
Worked example 2
A school sends each parent a short message of three lines: the student's name, the date of the meeting, and the room. Build it so that it has no blank first line and no indents, and check it with JSON.stringify.
What we have: a name, a date and a room
What we need: three clean lines
The plan: put the three lines in an array, build each with a template literal, and join them with \n
const name = "Asha";
const message = [
`Student: ${name}`,
"Meeting: Saturday, 10 am",
"Room: 12",
].join("\n");
console.log(JSON.stringify(message));
"Student: Asha\nMeeting: Saturday, 10 am\nRoom: 12"
Three lines, joined by \n, with no stray spaces.
Check: the printed text starts with Student and ends with 12, with nothing before or after.
A path that fails: one template literal laid out with the code's indentation. The parent's phone then shows a blank first line and every line pushed to the right.
When you are stuck: text has stray spaces or blank lines
Print it with JSON.stringify to see every space and \n.
Start a template literal's text right after the backtick, and its lines from the left edge.
Or build lines in an array and join them with \n.
trim() removes spaces and line breaks from the two ends, not from the middle.
Your turn
Why does `\n hello` look indented on screen?Tap to reveal
- The template keeps the line break and the two spaces before hello.
Because a template keeps every space and line break.
How many characters does "a\nb" have?Tap to reveal
- a, one line break, b.
3.
What does JSON.stringify show for a string that ends with a line break?Tap to reveal
- It writes the line break as \n inside the quotes.
A \n before the closing quote.
Did you know?
Two line endings made one
Some text files end each line with two characters, a carriage return and a line feed, a habit from many early computer systems. Inside a template literal, the standard turns that pair, and a lone carriage return too, into a single line feed, \n. So the same template gives the same string on every computer. A real carriage return needs an explicit escape.
Why it fits here: It answers this topic's question: inside a template literal, every kind of line ending becomes the same line feed.
Sources: ECMAScript Language Specification: Template Literal Lexical Components; Wikipedia: Newline
A proposal to strip the indent
The indentation trap has a proposed cure. TC39's String.dedent proposal would remove the common leading indentation from multiline template strings, so text can be indented along with the code around it. Its status is Stage 2: it is still a proposal, not part of JavaScript yet, so for now the text must start at the left edge or be joined from lines.
Why it fits here: It shows that this topic's indentation trap bothers the language's own committee enough to plan a built-in fix.
Source: TC39: String dedent proposal
In one line
A template literal keeps every line break and space, the code's indentation included. Start text right after the backtick, or join an array of lines with \n, and print with JSON.stringify to see what is hidden.
Numbers written for people
At a glance
A shop's bill writes ₹12,34,567, grouped the Indian way so the eye can read it, though the program stores the number with no commas at all. Numbers are written for people only when they are shown.
The method toLocaleString("en-IN") writes a number in Indian groups of lakhs and crores, and Intl.NumberFormat with the style currency and the currency INR writes rupees. Always name the locale, keep money in paise while working, and format only at the end, to show. One paisa is a hundredth of a rupee.
Take a guess: Where does a browser learn that India groups digits in lakhs and crores?
A bank statement in India writes twelve lakh thirty-four thousand five hundred sixty-seven as 12,34,567. An American one writes the same number as 1,234,567. Both are right, for their readers. The way a place writes numbers, dates and money is called its locale, and JavaScript can write numbers in any of them.
A method of every number that writes it the way a given locale does. (1234567).toLocaleString("en-IN") writes it for English as used in India, with Indian digit groups.
console.log((1234567).toLocaleString("en-IN"), (1234567).toLocaleString("en-US"));
12,34,567 1,234,567
The locale is written as a short code: en-IN is English as used in India, en-US English as used in the United States, hi-IN Hindi in India. Always name the locale. Without one, the method uses the computer's own setting, which may differ between your laptop and a customer's phone.
Rupees: Intl.NumberFormat
For money, the built-in object Intl, short for internationalisation, makes formatters. A formatter is made once with its options and then used for every amount:
A maker of number formatters. new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }) makes one that writes amounts as rupees in Indian groups, with the ₹ sign and two decimal places.
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log(inr.format(1234567.5), inr.format(450));
₹12,34,567.50 ₹450.00
The options change the details. maximumFractionDigits: 0 drops the paise for a round figure, and style: "percent" turns a fraction into a percentage:
const inr0 = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
console.log(inr0.format(250000), (0.5).toLocaleString("en-IN", { style: "percent" }));
₹2,50,000 50%
| Want | Write | Gives |
|---|---|---|
| Indian digit groups | n.toLocaleString("en-IN") | 12,34,567 |
| rupees with paise | Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }) | ₹12,34,567.50 |
| rupees, no paise | the same, with maximumFractionDigits: 0 | ₹2,50,000 |
| a percentage | { style: "percent" } | 50% |
| always two decimals | { minimumFractionDigits: 2 } | 1,234.50 |
Keep money in paise while you work, as the values lesson taught, and format only at the very end, when the amount is shown. The formatted text is for reading: it is a string, and its commas mean it can no longer be added up.
Worked example 3
A results portal shows a scholarship of ₹125000 and a score of 0.875. Show them as ₹1,25,000 and 87.5%.
What we have: an amount and a fraction
What we need: the two in Indian style, for reading
The plan: a rupee formatter with no decimals for the amount, and the percent style with one decimal place for the score
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
const score = (0.875).toLocaleString("en-IN", { style: "percent", maximumFractionDigits: 1 });
console.log(`Scholarship: ${rupees.format(125000)}, score: ${score}`);
Scholarship: ₹1,25,000, score: 87.5%
It shows Scholarship: ₹1,25,000, score: 87.5%.
Check: 0.875 is 87.5 per hundred, and 125000 is one lakh twenty-five thousand.
A path that fails: building the commas by hand, with slice and +. It works for one size of number and breaks for the next, while the formatter handles every size.
When you are stuck: a number is written the wrong way
Name the locale: en-IN for Indian groups.
For rupees, use Intl.NumberFormat with style currency and currency INR.
Format only at the end; the result is text and cannot be added.
If decimals are missing or extra, set minimumFractionDigits or maximumFractionDigits.
Your turn
console.log((100000).toLocaleString("en-IN"), (100000).toLocaleString("en-US"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1,00,000 100,000
- en-IN groups the last three digits, then pairs: 1,00,000.
- en-US groups in threes: 100,000.
It prints 1,00,000 100,000.
Why name the locale instead of writing n.toLocaleString() with no argument?Tap to reveal
- With no locale, the computer's own setting decides.
- A customer's setting may differ from yours.
So that every reader sees the same format.
Format 450 as ₹450.00.Tap to reveal
console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(450));
₹450.00
A currency formatter for INR gives ₹450.00.
Did you know?
Lakh and crore are built in
Browsers already know the lakh and the crore. MDN's own example of Intl.NumberFormat notes that India uses thousands, lakh and crore separators, and shows en-IN writing 1,23,456.789. The rules come from Unicode's CLDR, a shared store of locale data for programs around the world; its site lists Chrome and Android among the products that use it.
Why it fits here: It answers this topic's question: the Indian groups of en-IN come from a shared Unicode data store that browsers build in.
Sources: MDN: Intl.NumberFormat; Unicode CLDR Project
A sign from 2010
The rupee sign is young. It was designed by D. Udaya Kumar, an Indian academic and designer, and first presented to the public by the Government of India on 15 July 2010, after an open competition. Unicode gave it the code point U+20B9 in version 6.0, on 12 October 2010, calling it the new official Indian currency symbol.
Why it fits here: It gives this topic's rupees a history: the ₹ that Intl.NumberFormat writes has existed in computers only since late 2010.
Sources: Wikipedia: Indian rupee sign; Unicode 6.0.0
In one line
toLocaleString("en-IN") writes a number in Indian groups, and Intl.NumberFormat with style currency and INR writes rupees. Always name the locale, keep money in paise while working, and format only to show.
Text in straight columns
At a glance
A printed bill lines up its items: names on the left, prices on the right, every rupee under the one above. A program can line up text the same way, as long as each line is filled to the same width.
The method padEnd fills a text to a width at its end, and padStart at its start. Put names to the left with padEnd, and numbers to the right with padStart. Turn a number into a string first, cut a long name with slice, and on a web page use a table instead.
Take a guess: Why do padded columns line up in the console, but not always in a page's own font?
A printed bill lists names on the left and prices on the right, with the prices lined up under each other. Every line has the same width, and the gap between a name and its price changes with the name's length. Two methods make that gap.
A string method that adds characters at the end until the text has a given length. "Tea".padEnd(6, ".") gives Tea... with six characters; with no second argument it adds spaces.
padStart, met in the values lesson, does the same at the start. So padEnd pushes a name to the left of its column, and padStart pushes a number to the right of its column, which is where numbers belong, so that the units stand under the units:
const items = [
{ name: "Tea", price: 15 },
{ name: "Masala dosa", price: 80 },
{ name: "Lassi", price: 40 },
];
for (const item of items) {
console.log(item.name.padEnd(14, ".") + String(item.price).padStart(5));
}
Tea........... 15
Masala dosa... 80
Lassi......... 40
Every name becomes exactly 14 characters, filled with dots, and every price exactly 5 characters, filled with spaces in front. Each line is 19 characters, so the prices stand in a column. The price is turned into a string first with String, because padStart is a string method; a number does not have it.
When a name is too long
padEnd never cuts. A text already as long as the width, or longer, comes back unchanged, and its line is pushed out of step:
console.log("Paneer butter masala".padEnd(14, ".") + " 220");
console.log("Paneer butter masala".slice(0, 13).padEnd(14, ".") + " 220");
Paneer butter masala 220
Paneer butter. 220
Cutting the name with slice to one less than the width, and then padding it, keeps the column and leaves at least one dot between name and price. Decide what fits before you print: a receipt printer may have only 32 characters in a line.
Where columns of spaces work
Spaces line up only where every character has the same width, as in the console, a <pre> element, a text file or a receipt printer. On an ordinary web page, letters have different widths, so a list of prices there belongs in an HTML table, as the HTML step taught.
Worked example 4
The Clock Tower's canteen wants the day's bill as text, ready for its small printer: each item with its price in rupees, Indian style, and a total, all lined up in 24 characters.
What we have: a list of items with prices in rupees
What we need: lines of exactly 24 characters, prices on the right, and a total line
The plan: format each price with toLocaleString, pad names to 16 with padEnd and prices to 8 with padStart, and join the lines with \n
const items = [
{ name: "Thali", price: 1250 },
{ name: "Filter coffee", price: 340 },
];
const line = (label, amount) => label.padEnd(16, ".") + amount.toLocaleString("en-IN").padStart(8);
const total = items.reduce((sum, item) => sum + item.price, 0);
const lines = items.map((item) => line(item.name, item.price));
lines.push(line("Total", total));
console.log(lines.join("\n"));
Thali........... 1,250
Filter coffee... 340
Total........... 1,590
- map makes one line for each item, and push adds the total line at the end.
Three lines of 24 characters, with the total 1,590 under the prices.
Check: 1250 + 340 = 1590, and every line has 16 + 8 = 24 characters.
A path that fails: joining the name and price with a fixed number of spaces, such as name + " " + price. The gap is the same on every line, so the prices start at different places, and the bill looks ragged.
When you are stuck: columns do not line up
Check that every line is padded to the same widths: padEnd for text, padStart for numbers.
Turn numbers into strings before padding: String(n), or a formatted amount.
Cut names longer than their column with slice before padding.
On a web page, use a table: spaces line up only in a monospaced font.
Your turn
console.log("Dal".padEnd(6, "-") + "|", "7".padStart(3, "0"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Dal---| 007
- Dal has 3 characters; padEnd adds 3 dashes to reach 6.
- 7 becomes 3 characters with two zeros in front.
It prints Dal---| 007.
Why does (80).padStart(5) fail?Tap to reveal
- padStart belongs to strings, and 80 is a number.
- So it is not a function there: a TypeError.
Because numbers do not have padStart; write String(80).padStart(5).
What does "Chocolate".padEnd(5) give?Tap to reveal
- The text already has 9 characters, more than 5.
- padEnd never cuts.
The text Chocolate, unchanged.
Did you know?
Every letter the same width
Columns line up when every character takes the same width. The CSS standard defines a monospace font by exactly that: all glyphs have the same fixed width. The best known is Courier, designed in the mid-1950s by Howard Kettler for IBM. It was nearly called Messenger, until Kettler decided that a letter can be just an ordinary messenger, or it can be the courier.
Why it fits here: It explains why this topic's padded columns line up in the console: code is usually shown in a monospace font, where each character takes the same room.
Sources: CSS Fonts Module Level 4; Wikipedia: Courier (typeface)
Digits of equal width
A page can line up numbers without a monospace font. In many fonts the digits differ in width, so prices drift out of line. The CSS setting font-variant-numeric: tabular-nums switches on tabular numerals, figures that MDN describes as all of the same size, so they align as in tables. It suits a bill or a table of marks on a web page.
Why it fits here: It adds a tool for this topic's last advice: on a web page, tabular figures keep a column of numbers straight.
Sources: MDN: font-variant-numeric; CSS Fonts Module Level 4
In one line
padEnd fills a text to a width at the end, and padStart at the start: names to the left with padEnd, numbers to the right with padStart. Turn numbers into strings first, cut long names with slice, and use a table on a web page.
Tagged templates and String.raw
At a glance
A tag is a function written in front of a template literal, with no brackets: html`...`. Instead of joining the template into text, JavaScript calls the function.
The tag receives the pieces of text as an array, and the values of the gaps after them, always one fewer than the pieces. It returns whatever it likes, often a string. Libraries use tags to build HTML and CSS. String.raw is a built-in tag that keeps every backslash as it was written, so \n stays two characters.
Take a guess: Which popular libraries are built on tagged templates?
So far, every template literal has been put together in the ordinary way: the pieces of text and the gaps' values joined in order. A template literal can instead be handed to a function of your own, which receives the pieces and the values apart, and decides what to make of them.
A function name written straight before a template literal, with no brackets: tag`Hi ${name}`. The function, called the tag, is called with the template's pieces of text as an array, followed by the gaps' values, and what it returns is the result.
function show(strings, ...values) {
console.log(strings, values);
return "done";
}
const name = "Asha";
const due = 450;
console.log(show`Hi ${name}, you owe ${due}`);
[ 'Hi ', ', you owe ', '' ] [ 'Asha', 450 ]
done
Look at the two arrays. The pieces of text are Hi, then the text between the two gaps, then the text after the last gap, which is empty here. There is always one more piece than there are values, so the result can be built by taking a piece, a value, a piece, a value, and the last piece. The values arrive as they are: 450 is still a number, which the tag can format.
The three dots in ...values make a rest parameter: they gather all the remaining arguments into one array, however many gaps the template has. Lesson 03 of this step returns to the three dots.
A tag that formats rupees
Here is a tag that does real work: every value in the gaps is written as rupees in Indian groups, while the pieces of text stay as they are.
function inr(strings, ...values) {
let text = strings[0];
for (let i = 0; i < values.length; i++) {
text += "₹" + values[i].toLocaleString("en-IN") + strings[i + 1];
}
return text;
}
console.log(inr`Paid ${125000}, due ${4590}.`);
Paid ₹1,25,000, due ₹4,590.
The loop takes value 0 and piece 1, then value 1 and piece 2. Every amount in every message is now formatted the same way, by one function, and nobody can forget a comma.
String.raw: backslashes kept
A backslash starts an escape sequence: \n is a line break and \t a tab. A Windows path such as C:\new\table then turns into something else. The built-in tag String.raw keeps every backslash as written, as the template's raw text:
const path = String.raw`C:\new\table`;
console.log(path, path.length, `C:\new\table`.length);
C:\new\table 12 10
With String.raw, the path has its 12 characters, backslashes included. Without it, \n became one line break and \t one tab, which leaves 10 characters, two of them invisible. String.raw is useful for paths, and for the regular expressions of lesson 06, which use many backslashes.
| Written | Ordinary template | String.raw |
|---|---|---|
| \n | a line break | a backslash and n |
| \t | a tab | a backslash and t |
| \\ | one backslash | two backslashes |
| ${x} | x's value | x's value |
Worked example 5
A shop's messages must write every amount in rupees, and every message must read naturally. Using the inr tag, write the message for a refund of ₹1250 on order 77.
What we have: the inr tag, an amount and an order number
What we need: the message, with the amount formatted and the order number left alone
The plan: the inr tag formats every gap, which would put ₹ before the order number too; so build the order part as plain text first, and tag only the amount
function inr(strings, ...values) {
let text = strings[0];
for (let i = 0; i < values.length; i++) {
text += "₹" + values[i].toLocaleString("en-IN") + strings[i + 1];
}
return text;
}
const order = 77;
console.log(`Order ${order}: ` + inr`refund of ${1250} sent.`);
Order 77: refund of ₹1,250 sent.
It shows Order 77: refund of ₹1,250 sent.
Check: the order number has no ₹, and 1250 is written 1,250.
A path that fails: putting both numbers in one inr template. The tag cannot tell an order number from an amount, and writes Order ₹77.
When you are stuck: a tag gives an odd result
Print the two arrays the tag receives, as the first block does.
Remember there is one more piece of text than values, and the last piece may be empty.
Values arrive as they are: a number is still a number.
A tag is called without brackets: tag`...`, never tag(`...`), which passes one finished string.
Your turn
function count(strings, ...values) {
return strings.length + " " + values.length;
}
console.log(count`a${1}b${2}c${3}`);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4 3
- Three gaps give three values.
- The pieces are a, b, c and the empty text after the last gap: four.
It prints 4 3.
How long is String.raw`a\tb`?Tap to reveal
- String.raw keeps the backslash and the t.
- a, backslash, t, b.
4 characters.
What is the difference between tag`x` and tag(`x`)?Tap to reveal
- The first is a tagged template: the tag gets the pieces and values.
- The second makes a finished string first, and passes that one string.
Only the first hands the tag the pieces and the values.
Did you know?
Tags in the wild
Tags are not a curiosity: popular libraries are built on them. styled-components utilises tagged template literals to style React components, with real CSS written inside a template. Lit, a library for web components, writes its templates as template literals tagged with html. Both receive the pieces and the values separately, as every tag does.
Why it fits here: It answers this topic's question: styling and templating libraries use tags because a tag sees the pieces and the values apart.
LaTeX loosened the rules
Tagged templates once refused text such as \unicode, because a backslash and u must start a proper escape. MDN explains the change with LaTeX, whose commands often start with u or x: the rule that escape sequences must be well formed was removed from tagged templates, so String.raw can hold LaTeX as written. TC39's list names the change Lifting template literal restriction, by Tim Disney.
Why it fits here: It shows why this topic's String.raw can hold any backslash: the rule was relaxed for tags so that other languages could live inside them.
In one line
A tag is a function written before a template literal; it receives the pieces of text as an array and the values after them, one fewer, and returns the result. String.raw is a built-in tag that keeps backslashes as written.
Building HTML that a name cannot break
At a glance
A visitor's name can break a page. Type <b> into a name box, and if the page drops the name into HTML as it is, the browser reads it as a tag.
Text from a person must be escaped before it goes into HTML: the ampersand first, then the less-than, greater-than and quote signs, each turned into an entity. A tag can escape every gap at once and leave your own markup alone. And textContent needs no escaping at all, since it never reads text as HTML.
Take a guess: Has any browser built a method that cleans unsafe HTML by itself?
Template literals are a convenient way to build HTML: a card for each review, a row for each order. The DOM lesson showed the danger. When a person's text goes into a page with innerHTML, their tags become real elements, and a name such as <Ravi> disappears, or worse, runs a script.
<!DOCTYPE html>
<div id="list"></div>
<script>
const review = { name: "<b>Ravi</b>", text: "Good tea" };
document.getElementById("list").innerHTML = `<p>${review.name}: ${review.text}</p>`;
</script>
Checked in Chrome
- the name's tags became a real bold element: the visitor changed the page
The visitor typed tags, and the page obeyed them. The cure is to escape the text first: replace each character that HTML treats as special with its entity, the code that shows the character instead of obeying it. The HTML step met entities: < shows a < sign.
| Character | Its entity | Why it is special |
|---|---|---|
| & | & | it starts every entity |
| < | < | it starts a tag |
| > | > | it ends a tag |
| " | " | it ends an attribute's value |
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
console.log(escapeHtml('<b>"Great"</b> & cheap'));
<b>"Great"</b> & cheap
The ampersand is replaced first, on purpose. Every other replacement writes an ampersand of its own. If & were replaced last, the < made a moment earlier would become &lt;, and the visitor would see the code instead of the sign. The mistakes section shows it.
Escaped text in the page
With every value escaped, the same review is shown as text, angle brackets and all, and no element is made from it:
<!DOCTYPE html>
<div id="list"></div>
<script>
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
const review = { name: "<b>Ravi</b>", text: "Good tea" };
document.getElementById("list").innerHTML = `<p>${escapeHtml(review.name)}: ${escapeHtml(review.text)}</p>`;
</script>
Checked in Chrome
- no element was made from the name
- the name is shown as the visitor typed it
A tag that escapes every gap
Remembering to call escapeHtml in every gap is the weak point: one forgotten gap is enough. A tag can do it for every gap at once, while leaving the pieces of text, which are your own markup, as they are:
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
function html(strings, ...values) {
let text = strings[0];
for (let i = 0; i < values.length; i++) {
text += escapeHtml(values[i]) + strings[i + 1];
}
return text;
}
const name = "<Ravi>";
console.log(html`<p class="name">${name}</p>`);
<p class="name"><Ravi></p>
The tags you wrote, the p element and its class, come through untouched; the visitor's text is escaped. When a page only needs to show text, the DOM lesson's rule is still the plainest: put it in with textContent, which never reads tags at all.
Worked example 6
A school's notice board page shows each student's comment under their name. One student typed the comment <img src=x> to see what happens. Show the comment safely, with the html tag.
What we have: a list of comments, one with tags in it
What we need: every comment shown as typed, with no element made from it
The plan: build each card with the html tag, so that every gap is escaped, and join the cards
<!DOCTYPE html>
<div id="board"></div>
<script>
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
function html(strings, ...values) {
let text = strings[0];
for (let i = 0; i < values.length; i++) {
text += escapeHtml(values[i]) + strings[i + 1];
}
return text;
}
const comments = [
{ who: "Meera", text: "See you at practice" },
{ who: "Kabir", text: "<img src=x>" },
];
document.getElementById("board").innerHTML = comments.map((c) => html`<p><strong>${c.who}</strong>: ${c.text}</p>`).join("");
</script>
Checked in Chrome
- no image element was made from Kabir's comment
- both comments are on the board
- Kabir's comment is shown as typed
Both comments appear, and Kabir's shows <img src=x> as text.
Check: the checks under the block found no img element and the comment's text as typed.
A path that fails: escaping the whole finished card. The strong element that the page wrote itself is then escaped too, and the board shows its tags as text.
When you are stuck: a name or comment breaks the page
Find where the text goes into innerHTML, and escape it there.
Escape & first, then <, > and the quote.
Use a tag such as html so that no gap can be forgotten.
If the element only needs text, use textContent instead.
Your turn
What does escapeHtml give for "5 < 6"?Tap to reveal
- Only the < sign is special here.
- It becomes its entity.
The text 5 < 6, which a page shows as 5 < 6.
Why must & be replaced before <?Tap to reveal
- Replacing < writes <, which has an &.
- Replacing & after that would turn it into &lt;.
So that the entities made by the other replacements are not escaped again.
In the html tag, why are the pieces of text not escaped?Tap to reveal
- The pieces are the markup that you wrote.
- Only the gaps hold text from outside.
Because they are your own tags, which must stay tags.
Did you know?
A browser that cleans HTML
Browsers have started to clean HTML themselves. Firefox 148 added the Sanitizer API, whose element.setHTML() inserts HTML much as innerHTML does, but without security holes such as cross-site scripting. MDN describes it as parsing and sanitizing the string, removing elements and attributes that are unsafe. MDN still marks it as limited availability: some widely used browsers lack it.
Why it fits here: It looks ahead from this topic's escaping: a built-in cleaner may one day do the work for markup that must keep its tags.
Sources: Mozilla: Firefox 148 Release Notes; MDN: Element.setHTML()
And, by itself, and
The ampersand that must be escaped first has a name made of a sentence. When English letters were spelled aloud, a letter that was also a word was said with per se, Latin for by itself, and the sign & was called and per se and. Wikipedia explains that the phrase was slurred into ampersand, a word in common English use by 1837. The American Heritage Dictionary gives the same history.
Why it fits here: It names this topic's most important character: the ampersand, which must become an entity before any other sign does.
Sources: Wikipedia: Ampersand; The American Heritage Dictionary: ampersand
In one line
Text from a person must be escaped before it goes into HTML: & first, then <, > and the quote. A tag can escape every gap at once and leave your markup alone, and textContent needs no escaping at all.
Where it is used
Text for people is written in almost every program. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| choosing what a gap shows | every message a program shows | an order screen that reads Note: none instead of Note: null |
| text over many lines | messages, e-mails, reports | a three-line meeting message to a parent |
| toLocaleString and Intl.NumberFormat | amounts, scores and counts shown to people | a bank app writing ₹12,34,567.50 |
| padEnd and padStart | receipts, console reports, text files | a canteen's printed bill |
| tagged templates | formatting or escaping every gap in one place | an inr tag for every amount in a shop's messages |
| String.raw | file paths and regular expression patterns | a Windows path such as C:\new\table |
| escaping | every page that shows what people type | reviews, comments and names on a notice board |
Mistakes and debugging
These are the slips that people meet most often with this lesson's ideas. Every output below is the real one, from the code shown.
1. An object in a gap
const user = { name: "Asha" };
console.log(`Hi ${user}`);
Hi [object Object]
No error: the object was turned into text in the only way it knows. The fix: ${user.name}.
2. padStart on a number
const item = { name: "Tea", price: 15 };
console.log(item.name.padEnd(8) + item.price.padStart(4));
Uncaught TypeError: item.price.padStart is not a function
at line 2
The fix: String(item.price).padStart(4).
3. The ampersand escaped last
const bad = "<b>".replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&");
console.log(bad);
&lt;b&gt;
No error: the page shows the codes instead of the signs. The fix: replace & first.
4. A tag called with brackets
function inr(strings, ...values) {
let text = strings[0];
for (let i = 0; i < values.length; i++) {
text += "₹" + values[i].toLocaleString("en-IN") + strings[i + 1];
}
return text;
}
console.log(inr(`Paid ${500}`));
P
No error, and a strange answer. With brackets, the template was finished first, so the tag received one string and no values, and strings[0] was its first letter. The fix: inr`Paid ${500}`, with no brackets.
5. Adding formatted amounts
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log(inr.format(100) + inr.format(50));
₹100.00₹50.00
No error: formatted amounts are text, so + joined them. The fix: add the numbers, and format the total: inr.format(100 + 50).
6. Indentation inside a template
const msg = `
Paid`;
console.log(msg === "Paid", JSON.stringify(msg));
false "\n Paid"
No error: the template kept its line break and two spaces. The fix: start the text right after the backtick.
The debugging corner: look at the hidden characters
When text looks right but a comparison fails, or a column will not line up, print JSON.stringify(text) and text.length. Every line break shows as \n and every space is counted, so a stray character has nowhere to hide.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// gaps: choose the text yourself
const items = ["tea", "dal"];
const note = null;
console.log(`Items: ${items.join(", ")}. Note: ${note ?? "none"}`);
// numbers for people: name the locale, format only to show
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log((1234567).toLocaleString("en-IN"), inr.format(450));
// columns: names with padEnd, numbers with padStart
console.log("Tea".padEnd(10, ".") + String(15).padStart(6));
// a tag gets the pieces and the values; String.raw keeps backslashes
const tag = (strings, ...values) => `${strings.length} pieces, ${values.length} values`;
console.log(tag`a${1}b${2}c`, String.raw`C:\new`);
// escape a person's text before it goes into HTML: & first
const escapeHtml = (text) => String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
console.log(escapeHtml("<Ravi> & co"));
Items: tea, dal. Note: none
12,34,567 ₹450.00
Tea....... 15
3 pieces, 2 values C:\new
<Ravi> & co
| When you see | It means | Look at |
|---|---|---|
[object Object] in text | an object in a gap | a property, or JSON.stringify |
| words joined by commas with no spaces | an array in a gap | join(", ") |
| a blank first line, or stray indents | the template kept the code's line breaks and spaces | JSON.stringify, and text started right after the backtick |
TypeError: ... .padStart is not a function | padStart on a number | String(n) first |
| < shown on the page | the ampersand escaped after the others | escape & first |
| a visitor's tags working on the page | their text put in with innerHTML, unescaped | escapeHtml, an html tag, or textContent |
The story: A slip like a ledger
You teach the printer three things. Amounts are written in the city's own groups, ₹1,25,000, with the rupee sign in front. Every price is padded to the same width, so the column stands straight down the slip. And every name is written as plain text, its angle brackets and all.
The next slip comes out neat as a ledger, and the customer called <Ravi> finds his name on it, brackets included.
Master Verge files the slip in a drawer of good examples. "Text is a program's face," he says. "Most people never see anything else."
Reagents gathered: template literal, toLocaleString, Intl.NumberFormat, padEnd, tagged template, String.raw.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)