Strings & Template Literals
A string is a piece of text: a name, a message, an M-Pesa confirmation code. Almost every program builds, searches or cleans up text, so JavaScript gives strings plenty of built-in methods, plus template literals for building strings neatly.
Creating strings
You can write strings with double quotes, single quotes or backticks. Double and single quotes behave the same; pick one style and stick to it. Backticks create template literals, covered below.
const town = "Mombasa";
const greeting = 'Jambo';
const message = `Karibu ${town}`;
To include special characters inside quotes, use an escape sequence starting with a backslash:
console.log("Line one\nLine two");
console.log('It\'s mine');
console.log("She said \"Asante\"");
console.log("C:\\Users\\Amina");
\n is a new line, \' and \" are quote marks, and \\ is one real backslash. Often it is simpler to choose the other kind of quote: "It's mine" needs no escape.
Length and individual characters
A string is an ordered sequence of characters. .length tells you how many there are, and square brackets read one character by its index, counting from 0.
const town = "Mombasa"; console.log(town.length); console.log(town[0]); console.log(town[town.length - 1]); console.log(town.at(-1)); console.log(town[20]);
The last character is at index length - 1. The newer .at() method accepts negative numbers that count from the end, so .at(-1) is the last character. Reading past the end gives undefined, not an error.
Strings are immutable. town[0] = "X" does nothing (no error, no change), and town.toUpperCase(); on its own line is wasted, because the method returns a new string. Store the result: const loud = town.toUpperCase();.
Template literals
Gluing strings together with + gets messy quickly. A template literal is written between backticks and can contain placeholders written as a dollar sign followed by curly braces. Any JavaScript expression inside the braces is evaluated and inserted.
const name = "Wanjiru";
const item = "chapati";
const qty = 3;
const price = 20;
console.log(`${name} bought ${qty} ${item}s for KES ${qty * price}.`);
console.log(`Paid in full: ${qty * price <= 100 ? "yes" : "no"}`);
const receipt = `Item: ${item}
Quantity: ${qty}`;
console.log(receipt);
Template literals can also span several lines: the line break inside the backticks is kept in the string. Compare the first line with the old way, name + " bought " + qty + " " + item + "s for KES " + qty * price + ".", and you can see why modern code prefers templates.
Useful string methods
const raw = " Hello, Nairobi! ";
const text = raw.trim();
console.log(text);
console.log(text.toUpperCase());
console.log(text.includes("Nairobi"));
console.log(text.startsWith("Hello"));
console.log(text.indexOf("N"));
console.log(text.slice(7, 14));
console.log(text.replace("Nairobi", "Kampala"));
console.log(text.split(", "));
| Method | What it returns |
|---|---|
trim(), trimStart(), trimEnd() | A copy without surrounding spaces (great for form input) |
toUpperCase(), toLowerCase() | A copy in upper or lower case |
includes(s), startsWith(s), endsWith(s) | true or false |
indexOf(s) | Position of the first match, or -1 if not found |
slice(start, end) | The part from start up to, but not including, end |
replace(a, b), replaceAll(a, b) | A copy with the first (or every) a replaced by b |
split(separator) | An array of pieces |
padStart(n, ch), repeat(n) | A padded or repeated copy: "7".padStart(3, "0") is "007" |
In "Hello, Nairobi!" the letter N sits at index 7 (H is 0, the comma is 5, the space is 6), so slice(7, 14) takes indexes 7 to 13, the word "Nairobi". String searches are case-sensitive: text.includes("nairobi") is false. To search without caring about case, lower-case both sides first.
Strings and numbers
Values typed into a form always arrive as strings, even if they look like numbers. Convert them before doing maths with Number("42"), and turn numbers into text with String(42) or a template literal. Mixing them by accident causes the classic "5" + 5 === "55" bug. See Numbers & Math for the details.
Key points
- Strings use quotes or backticks; escape special characters with a backslash.
- Indexes start at 0;
.lengthcounts characters and.at(-1)gives the last. - Template literals insert expressions with a dollar sign and curly braces and can span lines.
- String methods return new strings; the original never changes.
Tip: use the ← and → keys to move between pages.
