Strings and Template Literals

Store text in strings, build messages from your values with template literals, and tidy and search text with length, trim, toUpperCase and includes.

Novice · JavaScript · Updated

After this lesson you can

  • Build text from values with a template literal
  • Use a string's length, toUpperCase, includes and trim

Key takeaways

  • A string is text in quotes. Single quotes and double quotes both work; pick one and stay with it.
  • A template literal is text in backticks, and each ${} in it is a blank that JavaScript fills with a value.
  • length counts a string's characters, spaces included.
  • trim() removes the spaces at the ends, toUpperCase() gives capitals, and includes() says whether some text is inside.
  • String methods hand back a new string; the original stays as it was.

"Hi, Sam! Your oat milk latte is ready." "You have 3 stamps to go." "Order #42: $9.50." Almost every message an app shows you is a sentence with a few values dropped in, and the sentence stays the same while the values change. In this lesson you'll store text, build messages like these, and clean up what people type.

Text is a string

Think of a necklace of letter beads that spells a name: one bead per letter, space or punctuation mark, in order. In programming, a piece of text is called a string, as in a string of characters.

You write a string in quotes. Single quotes ' and double quotes " both work, as long as the two ends match. You'll see both in this course and in real code; pick one and stay with it within a file.

const shopName = 'The Daily Grind';
const special = "Pumpkin spice latte";

console.log(shopName);
console.log(special);
The Daily Grind
Pumpkin spice latte

The quotes aren't part of the text: they show JavaScript where it starts and ends. That's why a string such as 'It's fresh' breaks: the ' in It's ends the string early. Write "It's fresh" instead.

Joining strings with +

Between two strings, + joins them end to end. That's called concatenation, read "con-cat-en-AY-shun", or "concat" for short:

const customer = 'Sam';
const drink = 'latte';

console.log('Order for ' + customer + ': 1 ' + drink);
console.log('Order for' + customer);
Order for Sam: 1 latte
Order forSam

+ adds no spaces of its own, as the second line shows: every space has to be inside a string. With a few values in one message, the quotes and pluses pile up and spaces go missing. There's a better way.

Template literals: a sentence with blanks

Picture a fill-in-the-blank form: the sentence is printed, and the blanks are filled in for each person. A template literal is that form, in code. It's text between backticks ` (the key to the left of 1 on most keyboards, read "backtick"), and each blank is written ${}, read "dollar sign, curly braces". Whatever is inside the braces is worked out and dropped into the text. Filling the blanks is called string interpolation.

const customer = 'Sam';
const drink = 'oat milk latte';
const price = 4.75;

console.log(`Hi, ${customer}! Your ${drink} is ready.`);
console.log(`Two of them: ${(price * 2).toFixed(2)}`);
Hi, Sam! Your oat milk latte is ready.
Two of them: $9.50

In ${, the first $ is a plain dollar sign that gets printed, and ${ starts the blank. A blank can hold a whole calculation, like (price * 2).toFixed(2). The toFixed(2) shows two decimal places, from Numbers and Math.

A template literal can span lines

A template literal keeps its line breaks, which makes it handy for something like a receipt:

const customer = 'Sam';
const total = 9.5;

const receipt = `The Daily Grind
Order for ${customer}
Total: ${total.toFixed(2)}
Thanks for stopping by!`;

console.log(receipt);
The Daily Grind
Order for Sam
Total: $9.50
Thanks for stopping by!

${} only works inside backticks. In single or double quotes, '${customer}' is printed exactly as written, dollar sign and all.

Try it. In your practice folder, make a file named ready.js. Store a customer's name, a drink and a size in variables, and print Medium cold brew for Ana, coming right up! with a template literal. Then change the values and run it again.

Length and a few string methods

A string can tell you things about itself and make changed copies of itself. You ask with a dot after the string:

  • .length, read "dot length", is how many characters it has, spaces included.
  • A method is something a value can do, written with parentheses: trim() gives a copy without the spaces at the ends, toUpperCase() gives a copy in capitals, and includes('oat') answers true or false: is that text inside?

A customer types their order into the app with a stray space at each end:

const order = ' oat milk latte ';

console.log(order.length);
console.log(order.trim().length);
console.log(order.trim().toUpperCase());
console.log(order.includes('oat'));
console.log(order.includes('Oat'));
16
14
OAT MILK LATTE
true
false

includes is case-sensitive: oat is in the order, Oat isn't. order.trim().toUpperCase() does two things in a row: trim() makes a trimmed copy, then toUpperCase() makes a capital copy of that. true and false are values of their own, the subject of the next lesson.

One thing to notice: these methods never change order itself. After all those lines, order still has its spaces. To keep a cleaned-up version, store it: const cleanOrder = order.trim();.

Try it. Store a name typed with extra spaces, such as ' jordan '. Print its length before and after trim(), then print a greeting with the trimmed name in capitals, using a template literal.

Check yourself

2 questions to try on the lesson page.

So what

Names on a screen, order confirmations, error messages and search boxes are all strings. Template literals let you build any message from your values, and a few string methods let you tidy and check what people type.

Key terms

Cheat sheets

Related