SyntaxPilot
Courses/JavaScript/Lesson 4
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 4 of 40

Strings and template literals

queued

These are the notes for JavaScript episode 4. You will learn what a string is, the three kinds of quotes, escape characters, length and indexes, why strings are immutable, the everyday string methods (trim, toUpperCase, toLowerCase, includes, startsWith, endsWith, indexOf, slice, padStart, padEnd, split, replace, replaceAll), why building messages with + breaks, and template literals with ${}. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

What a string is: Ravi's chai stall goes online

Ravi runs a chai stall and now takes orders on WhatsApp. Every reply his app sends is text: "Hi Priya, your 2 samosas are ready." Names, items, phone numbers, emails: all text.

At Ravi's stall In JavaScript
A WhatsApp reply a string
The letters strung on a thread the characters of the string
Where the message starts and ends the quotes

A string is a piece of text: characters strung together. You write it inside quotes. JavaScript has three kinds, and single and double quotes behave exactly the same:

const a = 'chai';     // single quotes
const b = "chai";     // double quotes
const c = `chai`;     // backticks: a template literal (see below)
console.log(typeof c);
string

The quote trap

Write the shop's name in single quotes:

const shop = 'Ravi's Chai';
console.log(shop);
const shop = 'Ravi's Chai';
                   ^

SyntaxError: Unexpected identifier 's'

The apostrophe in Ravi's is also a single quote, so JavaScript thinks the string ended after Ravi. Then it finds a stray s that means nothing. Because it's a SyntaxError, Node refuses to run even line 1.

Two fixes: use the other kind of quote on the outside, or put a backslash before the inner quote:

console.log("Ravi's Chai");
console.log('Ravi\'s Chai');
console.log("Line 1\nLine 2");
console.log("Item\tPrice");
Ravi's Chai
Ravi's Chai
Line 1
Line 2
Item    Price

Escape characters

A backslash says "the next character is special". These are called escape characters (escape sequences):

You write You get
\' a single quote ' inside '...'
\" a double quote " inside "..."
\` a backtick inside `...`
\n a new line
\t a tab
\\ one backslash \
console.log("A" + "\\" + "B");
A\B

A normal '...' or "..." string cannot contain a real line break. This is a SyntaxError:

const msg = "Hi
there";
SyntaxError: Invalid or unexpected token

Use \n, or a template literal (which can span lines).

length and indexes: a garland of beads

Picture a string as a garland of beads, one character per bead.

A bead garland In JavaScript Result for "Priya"
Count the beads name.length 5
Bead numbers start at 0 name[0] "P"
The last bead name.at(-1) "a"
  • length is the number of characters (spaces count too). It's a property, not a method: no brackets.
  • Each character has a position called its index, and indexes start at 0. The last index is always length - 1.
  • .at(-1) counts from the end: -1 is the last character, -2 the one before it.
const msg = "Your OTP is 4821";
console.log(msg.length);
const name = "Priya";
console.log(name[0]);
console.log(name[4]);
console.log(name[5]);
console.log(name.at(-1));
16
P
a
undefined
a

name[5] is past the end: there is no sixth bead, so you get undefined. JavaScript doesn't crash, it just says nothing is there.

Strings are immutable: the printed bill

A customer saved her name as priya, with a small p. The obvious fix is to swap the first letter:

let name = "priya";
name[0] = "P";
console.log(name);
priya

No error, no change. A string is like a printed bill: you can't rub out one letter. Once a string is created, it never changes. That is what immutable means.

In strict mode (which modules and classes use automatically, and which you can turn on with "use strict"; at the top of a file), the same line is an error instead of being silently ignored:

"use strict";
let name = "priya";
name[0] = "P";
TypeError: Cannot assign to read only property '0' of string 'priya'

Methods return a NEW string

Strings come with built-in tools called methods, written string.method(). A string method never edits the original; it returns a brand-new string:

let name = "priya";
name[0] = "P";
console.log(name);
console.log(name.toUpperCase());
console.log(name);
name = name.toUpperCase();
console.log(name);
priya
PRIYA
priya
PRIYA

To keep the new string, store it back (name = name.toUpperCase()), which is why name was declared with let. Calling the method and ignoring the result does nothing:

const name = "Priya";
name.toUpperCase();
console.log(name);
Priya

Cleaning text: trim, case and chaining

Priya's email is saved as priya@gmail.com. On her phone, auto-capitalize and stray spaces turn it into " Priya@Gmail.com ". To a human it's the same email; === compares every character, including spaces and capitals:

const saved = "priya@gmail.com";
const typed = "  Priya@Gmail.com ";
console.log(typed === saved);
console.log(typed.trim().toLowerCase() === saved);
false
true
  • trim() removes spaces (and tabs and new lines) from both ends. trimStart() and trimEnd() do one end each.
  • toLowerCase() / toUpperCase() change every letter.
  • Writing methods one after another, typed.trim().toLowerCase(), is called chaining: each method works on the string the previous one returned.
console.log("  hi  ".trimStart() + "|");
console.log("  hi  ".trimEnd() + "|");
hi  |
  hi|

Rule: clean input before you compare it. Every real login form does this.

Searching inside text

Ravi checks In JavaScript Answer
Is it an Indian number? phone.startsWith("+91") true / false
Is the menu a PDF? file.endsWith(".pdf") true / false
Does it mention samosa? msg.includes("samosa") true / false
Where is the first space? phone.indexOf(" ") an index, or -1
const phone = "+91 98765 43210";
console.log(phone.startsWith("+91"));
console.log(phone.includes("98765"));
console.log("bill.pdf".endsWith(".pdf"));
console.log(phone.indexOf(" "));
console.log(phone.indexOf("#"));
true
true
true
3
-1

indexOf returns the index of the first match, or -1 for "not found". lastIndexOf finds the last match. All of these are case-sensitive:

console.log("Masala chai".indexOf("chai"));
console.log("chai".lastIndexOf("a"));
console.log("Chai".includes("chai"));
7
2
false

Cutting text: slice and padStart

A delivery partner shouldn't see the customer's full phone number. Food apps show only the last four digits.

const phone = "9876543210";
const last4 = phone.slice(-4);
console.log(last4);
console.log(phone.slice(0, 2));
console.log(last4.padStart(10, "*"));
3210
98
******3210

The slice(start, end) rule

Call Result Why
"9876543210".slice(0, 2) "98" start included, end not included
"9876543210".slice(-4) "3210" negative counts from the end
"9876543210".slice(6) "3210" no end: goes to the end
"Hello".slice(1, 3) "el" index 1 and 2

padStart(length, fill) adds the fill characters at the front until the string is length long; padEnd adds them at the back. Great for masks, order numbers ("0007") and lining up a bill.

slice vs substring

There is an older method, substring, that looks the same but behaves differently with unusual arguments:

console.log("Hello".substring(3, 1));
console.log("Hello".slice(3, 1));
console.log("Hello".slice(-3));
console.log("Hello".substring(-3));
el

llo
Hello

substring swaps the arguments if start > end and treats negatives as 0; slice returns "" and supports negatives. Prefer slice. (Avoid substr; it's deprecated.)

split and replace

Customers type a whole order on one line: "chai,samosa,vada pav".

The order slip In JavaScript Result
Cut at every comma order.split(",") a list of 3 items
Swap the first chai replace("chai", "coffee") first match only
Swap every chai replaceAll("chai", "coffee") every match
const order = "chai,samosa,vada pav";
const items = order.split(",");
console.log(items);
console.log(items.length);
const song = "chai chai chai";
console.log(song.replace("chai", "coffee"));
console.log(song.replaceAll("chai", "coffee"));
[ 'chai', 'samosa', 'vada pav' ]
3
coffee chai chai
coffee coffee coffee

split returns an array: a list of values in square brackets (arrays get their own episode, episode 7). join does the reverse:

console.log("chai".split(""));
console.log(["chai", "samosa"].join(", "));
[ 'c', 'h', 'a', 'i' ]
chai, samosa

Building messages with +: the two bugs

The app must build the order message from variables:

const name = "Priya";
const qty = 2;
const item = "samosa";
const price = 20;
const msg = "Hi " + name + ", your " + qty + " " + item +
  "s are ready." + "Total: Rs " + qty * price;
console.log(msg);
console.log("With tip: Rs " + qty * price + 5);
Hi Priya, your 2 samosas are ready.Total: Rs 40
With tip: Rs 405

Two bugs:

  1. ready.Total — a space was forgotten inside one of the many quotes. With so many quotes and + signs, it's hard to see.
  2. Rs 405 instead of Rs 45 — left to right, "With tip: Rs " + 40 became the string "With tip: Rs 40", and then + 5 glued a 5 on the end (the + trap from episode 3).

Template literals: a fill-in-the-blanks form

Think of a printed form with blanks: "Hi _, your _ samosas are ready." You write the sentence once, naturally, and fill in the blanks.

A printed form In JavaScript
A form with blanks a string in backticks `...`
Fill in each blank ${name}: a placeholder
A blank can hold a sum ${qty * price}: any expression

A template literal is a string written between backticks (the key under Esc, top left of most keyboards). Inside it, ${ ... } is a placeholder: JavaScript evaluates the expression inside and puts the result into the string. This is called string interpolation.

const name = "Priya";
const qty = 2;
const item = "samosa";
const price = 20;
const msg = `Hi ${name}, your ${qty} ${item}s are ready.`;
const total = `Total: Rs ${qty * price}`;
console.log(`${msg} ${total}`);
console.log(`With tip: Rs ${qty * price + 5}`);
Hi Priya, your 2 samosas are ready. Total: Rs 40
With tip: Rs 45

The space is visible where it belongs, and the maths inside ${} runs first, so the tip total is correct. Anything that produces a value works inside ${}:

console.log(`2 + 3 = ${2 + 3}`);
console.log(`${"ok".toUpperCase()}!`);
2 + 3 = 5
OK!

Multi-line strings

Template literals can span several lines, exactly as typed, and single quotes inside them need no escaping:

const item = "samosa";
const qty = 2;
const receipt = `--- Ravi's Chai ---
Item: ${item} x ${qty}
Total: Rs ${qty * 20}
Thank you!`;
console.log(receipt);
--- Ravi's Chai ---
Item: samosa x 2
Total: Rs 40
Thank you!

${} only works in backticks

const name = "Priya";
console.log("Hi ${name}");
console.log(`Hi ${name}`);
Hi ${name}
Hi Priya

In normal quotes, ${name} is just plain text. No error — a wrong message silently goes to the customer.

String methods reference

Method / property What it does Example Result
length number of characters "chai".length 4
[i] / at(i) character at index (at allows negatives) "chai".at(-1) "i"
toUpperCase() / toLowerCase() change case "Chai".toLowerCase() "chai"
trim() / trimStart() / trimEnd() remove spaces at the ends " hi ".trim() "hi"
includes(x) contains x? "chai".includes("ha") true
startsWith(x) / endsWith(x) begins / ends with x? "a.pdf".endsWith(".pdf") true
indexOf(x) / lastIndexOf(x) first / last position, or -1 "chai".indexOf("a") 2
slice(start, end) piece from start up to (not incl.) end "Hello".slice(1, 3) "el"
padStart(n, f) / padEnd(n, f) fill up to length n "7".padStart(4, "0") "0007"
split(sep) cut into an array "a-b-c".split("-") ['a','b','c']
replace(a, b) / replaceAll(a, b) swap first / every match "aa".replaceAll("a","b") "bb"
repeat(n) repeat n times "ab".repeat(3) "ababab"
String(x) convert to a string String(7) "7"

Every method returns a new value; the original string is never changed.

Common mistakes (and what really happens)

You wrote What happens Why Fix
'Ravi's Chai' SyntaxError: Unexpected identifier 's' the ' ended the string "Ravi's Chai" or 'Ravi\'s Chai'
"Hi + a real line break + there" SyntaxError: Invalid or unexpected token normal quotes can't span lines \n or backticks
name[0] = "P" (no error) nothing changes strings are immutable name = name.toUpperCase()
name[0] = "P" in strict mode TypeError: Cannot assign to read only property '0' of string 'priya' strings are immutable build a new string
name.toUpperCase(); (result ignored) (no error) name unchanged methods return a new string store the result
"chai".length() TypeError: "chai".length is not a function length is a property "chai".length
name[5] on "Priya" (no error) undefined past the last index (4) last = length - 1 or .at(-1)
typed === saved with stray spaces/capitals (no error) false === compares every character typed.trim().toLowerCase()
"Rs " + 40 + 5 (no error) "Rs 405" + glues left to right `Rs ${40 + 5}`
"Hi ${name}" (no error) prints Hi ${name} ${} only works in backticks `Hi ${name}`
let s; s.length TypeError: Cannot read properties of undefined (reading 'length') s has no string yet give it a value first

Mini project: a chai stall receipt

The customer's name arrives messy, the order number must look like 0007, the receipt should line up, and the phone number must be masked.

// Mini project: a chai stall receipt
const customer = "  priya sharma ";
const item = "Masala chai";
const qty = 3;
const price = 15;
const name = customer.trim().toUpperCase();
const orderNo = String(7).padStart(4, "0");
console.log(`Order #${orderNo} for ${name}`);
console.log(`${item.padEnd(14, ".")} ${qty} x Rs ${price}`);
console.log(`${"Total".padEnd(14, ".")} Rs ${qty * price}`);
console.log(`Phone: ${"9876543210".slice(-4).padStart(10, "*")}`);
Order #0007 for PRIYA SHARMA
Masala chai... 3 x Rs 15
Total......... Rs 45
Phone: ******3210

What each line uses:

  • trim() + toUpperCase() (chained) clean the name.
  • String(7) turns the number into text so padStart(4, "0") can fill it to "0007".
  • padEnd(14, ".") makes the item and "Total" the same width, so the prices line up.
  • slice(-4) + padStart(10, "*") mask the phone number.
  • Template literals put it all together, with the maths qty * price inside ${}.

Try changing the customer, the item and the quantity.

Practice

  1. Print the first and the last letter of your name (two ways for the last one).
  2. Mask an email: "priya@gmail.com" → "p****@gmail.com".
  3. Count the items in "tea,coffee,lassi,juice".
  4. Rewrite "Hi " + n + ", your " + q + " " + it + "s are ready." as a template literal.
Solutions and hints
const name = "Anurag";
console.log(name[0], name[name.length - 1], name.at(-1));
A g g
  1. Find the @, keep the first letter, replace the rest of the name with stars:
const email = "priya@gmail.com";
const at = email.indexOf("@");
console.log(email[0] + "*".repeat(at - 1) + email.slice(at));
p****@gmail.com
  1. split it and take the array's length:
console.log("tea,coffee,lassi,juice".split(",").length);
4
const n = "Priya", q = 2, it = "samosa";
console.log(`Hi ${n}, your ${q} ${it}s are ready.`);
Hi Priya, your 2 samosas are ready.

Quick quiz

What does this print?

const word = "Hello";
console.log(word.slice(1, 3));
  • A. "He"
  • B. "el"
  • C. "ell"
  • D. "Hel"
Answer

B. Indexes: H=0, e=1, l=2, l=3. slice(1, 3) starts at index 1 and stops before index 3, so you get indexes 1 and 2: "el".

Interview questions

  • What does it mean that strings are immutable in JavaScript? What happens with str[0] = "X"?
  • What's the difference between single quotes, double quotes and backticks?
  • What is a template literal? What can go inside ${}?
  • What's the difference between slice and substring?
  • What does indexOf return when the text isn't found?
  • What's the difference between replace and replaceAll?
  • Why does "Rs " + 40 + 5 give "Rs 405"? How do you fix it?
  • How would you compare two emails typed by users so that " A@x.com" equals "a@x.com"?
  • Is length a method or a property?

Glossary

Term Meaning Example
String a piece of text; a sequence of characters "chai"
Character one letter, digit, space or symbol in a string "a", " "
Quotes mark where a string starts and ends '...', "..."
Backtick the ` key; starts a template literal `chai`
Escape character a backslash sequence for a special character \n, \', \t
length the number of characters (a property) "chai".length → 4
Index a character's position, starting at 0 "chai"[0] → "c"
at() character at an index; negatives count from the end "chai".at(-1) → "i"
Immutable can never be changed once created strings
Method a built-in tool called with a dot and brackets name.toUpperCase()
Property a value attached to something, no brackets name.length
Return value what a method gives back "priya".toUpperCase() → "PRIYA"
Chaining calling methods one after another s.trim().toLowerCase()
trim removes spaces from both ends " hi ".trim() → "hi"
includes / startsWith / endsWith does the text contain / begin / end with...? phone.startsWith("+91")
indexOf position of the first match, or -1 "chai".indexOf("a") → 2
slice copies a piece from start up to (not including) end "Hello".slice(1, 3) → "el"
padStart / padEnd fill a string up to a length "7".padStart(4, "0") → "0007"
split cuts a string into an array "a,b".split(",")
Array a list of values in square brackets ['chai', 'samosa']
replace / replaceAll swap the first / every match "aa".replace("a", "b") → "ba"
Concatenation gluing strings with + "Hi " + name
Template literal a string in backticks with placeholders `Hi ${name}`
Placeholder ${} a blank in a template literal, filled with a value ${qty}
Interpolation putting values into a string through placeholders `Total: ${a + b}`
Expression any piece of code that produces a value qty * price
Strict mode a stricter JavaScript mode where silent mistakes become errors "use strict";

Summary

  • A string is text in '...', "..." or `...`. Escape special characters with \ (\', \n, \t).
  • length counts characters; indexes start at 0; the last is length - 1 or .at(-1).
  • Strings are immutable: methods return new strings, so store the result.
  • Clean input with trim() and toLowerCase() before comparing.
  • Search with includes, startsWith, endsWith, indexOf (-1 = not found).
  • Cut with slice(start, end) (end not included), fill with padStart/padEnd, split into arrays with split, swap with replace/replaceAll.
  • Build messages with template literals: `Hi ${name}, total Rs ${qty * price}`, multi-line allowed. ${} only works in backticks.

Next episode: if/else, switch and the ternary operator. Ravi's app must give discounts only to big orders and greet customers by the time of day, so you'll teach your program to make decisions.