EduFlow
JavaScript Fundamentals
0%

Section 1 · First Steps

Strings and Template Literals

16 min3 min readCode playground

Lesson at a glance

Create and clean up strings, read characters by index, use the everyday string methods, and build readable output such as “Lunch: $12.20” with template literals.

  1. 1Writing strings
  2. 2Template literals: values inside text
  3. 3Characters, positions and slices
  4. 4Methods that return new strings
  5. 5Strings and numbers, back and forth
  6. 6Comparing strings

No video here — just the real thing: a written lesson, runnable examples, a quiz and practice.

Pocket’s numbers are exact now, but nobody wants to read 1220. People want Lunch: $12.20. Text in JavaScript is a string, and most of what a user ever sees from your program is a string you built.

Writing strings

You can write a string with single quotes, double quotes or backticks:

JavaScript
const a = 'Coffee';
const b = "Sam's lunch";
const c = `Bus`;
console.log(a, b, c);

Single and double quotes behave the same; pick one style and stick to it (this course uses double quotes). Use the other kind when your text contains a quote, as in "Sam's lunch", or escape it with a backslash: 'Sam\'s lunch'. \n inside a string is a line break.

Backticks are special, and you will use them most. They make template literals.

Template literals: values inside text

Joining strings with + gets messy quickly: "Lunch:

quot; + dollars + " (" + category + ")". It is easy to forget a space or a quote. A template literal lets you write the text once and drop values into it with ${ }:

JavaScript
const label = "Lunch";
const cents = 1220;
const category = "food";

const line = `${label}: ${(cents / 100).toFixed(2)} (${category})`;
console.log(line);

Anything inside ${ } is a full JavaScript expression. It is evaluated, turned into a string, and inserted. Here (cents / 100).toFixed(2) divides to get 12.2, and toFixed(2) turns that into the string "12.20" with exactly two decimals. The first $ is a plain dollar sign; only $ followed by { starts an insertion.

Template literals can also span lines, which is handy for multi-line messages:

JavaScript
const report = `Pocket summary
  Spent: $22.00
  Left:  $3.00`;
console.log(report);

Characters, positions and slices

A string is a sequence of characters, and each one has a position called an index, counting from 0. length tells you how many characters there are.

The string Coffee has six characters at indexes 0 to 5. slice(0, 3) copies indexes 0, 1 and 2, giving Cof, and stops before index 3. C o f f e e 0 1 2 3 4 5 index slice(0, 3) → "Cof" stops before 3
Indexes start at 0, and slice stops before its end index
JavaScript
const word = "Coffee";
console.log(word.length);      // 6
console.log(word[0]);          // first character
console.log(word.at(-1));      // last character
console.log(word.slice(0, 3)); // from index 0 up to, not including, 3
console.log(word.slice(3));    // from index 3 to the end

word.at(-1) counts from the end, which saves you writing word[word.length - 1].

Methods that return new strings

Strings come with built-in methods, functions you call with a dot. The ones you will use weekly:

JavaScript
const raw = "  Coffee with Sam  ";
const clean = raw.trim();

console.log(clean);                      // spaces removed from both ends
console.log(clean.toUpperCase());
console.log(clean.includes("Sam"));      // true or false
console.log(clean.startsWith("Coffee"));
console.log(clean.replaceAll(" ", "-"));
console.log("7".padStart(3, "0"));       // "007"
console.log(`[${raw}]`);                 // the original is untouched

That last line is the key idea: strings are immutable. No method ever changes a string; each one returns a new string. If you want to keep the result, store it.

Combining methods is common. To capitalise the first letter of a label, take the first character, uppercase it, and add the rest:

JavaScript
const label = "groceries";
const nice = label[0].toUpperCase() + label.slice(1);
console.log(nice);

Two more methods answer “where is it?” rather than “is it there?”. indexOf("Sam") returns the index where the text first appears, or -1 when it is not there at all. And split(" ") cuts a string into pieces wherever it finds the separator and gives you back a list, ["Coffee", "with", "Sam"]. Lists are called arrays, and they get a whole lesson in section 3.

Strings and numbers, back and forth

Pocket constantly crosses the border between text and numbers. Amounts are numbers while you calculate and strings when you display them; typed input is a string until you convert it.

JavaScript
const cents = 450;
console.log(String(cents), typeof String(cents));  // number to string
console.log(`${cents}`.length);                    // a template literal converts too
console.log(Number("4.50") * 100);                 // string to number
console.log(Number("  12 "));                      // spaces around digits are ignored
console.log(Number(""));                           // careful: an empty string becomes 0

The last line is a trap worth remembering. An empty text box converts to 0, not NaN, so “the user typed nothing” looks exactly like “the user typed zero”. When you validate forms in section 4, you will check for empty input before converting.

Comparing strings

=== compares strings character by character, and it is case-sensitive: "Food" === "food" is false. Users type categories however they like, so normalise before you compare: trim the spaces and pick one case.

JavaScript
const typed = "  Food ";
console.log(typed === "food");                       // false
console.log(typed.trim().toLowerCase() === "food");  // true

You can also use < and > on strings. They compare character codes one position at a time, which works for simple lowercase words ("apple" < "banana" is true) and goes wrong quickly beyond that: "Zebra" < "apple" is also true, because every uppercase letter has a smaller code than every lowercase one. Section 3 shows the right way to sort text, with localeCompare, which follows the rules of a real language.

Pocket can now hold amounts, calculate with them exactly and print them in a form people can read. What it cannot do yet is react: warn you when you go over budget, or treat food differently from rent. In the next section your program starts making decisions.

Key takeaways

  • Strings can use single quotes, double quotes or backticks; backticks make template literals, which can insert values with ${} and span several lines.
  • Strings are immutable, so methods like trim() and toUpperCase() return a new string and leave the original unchanged.
  • Characters are numbered from 0, length counts them, and slice(start, end) copies a piece up to, but not including, end.
  • Format cents for display with (cents / 100).toFixed(2) or Intl.NumberFormat, and keep the stored amount as a number.

Further reading

Check your understanding

3 questions

Question 1 of 3

What does this print?

JavaScript
let label = "  lunch ";
label.trim();
console.log(`[${label}]`);
Question 2 of 3

const word = "Pocket"; Which expression gives "Poc"?

Question 3 of 3

You need to show 1220 cents as $12.20. Which is right?

Practice

Code playground

Format an expense line

An expense arrived from a form with messy text. Build the string line so that it reads exactly Coffee with Sam: $4.50 (food), then log it. Use the variables: trim rawLabel and capitalise its first letter, show cents as dollars with two decimals, and lowercase category. A template literal keeps this readable.

// An expense as it arrived from a messy form
const rawLabel = "   coffee with Sam ";
const cents = 450;
const category = "FOOD";

// Build line so it reads exactly: Coffee with Sam: $4.50 (food)
const line = rawLabel + ": " + cents + " (" + category + ")";
console.log(line);
Loading the editor…

Ctrl/⌘ + Enter to run · Runs in a sandbox in your browser. Nothing leaves your device.

Console

(no output)

Checks

  • Starts with a capital C and has no stray spaces
  • Shows the amount as $4.50
  • line is exactly “Coffee with Sam: $4.50 (food)”
  • Logs the line