Strings and template literals
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
Strings are everywhere
Names, messages, URLs, form input and API data are all strings. You will work with them constantly, so it is worth knowing the main tools well.
A string is a sequence of characters. You write it with single quotes, double quotes or backticks.
const single = 'Lahore';
const double = "Pakistan";
const backtick = `Punjab`;
Pick single or double quotes and stay consistent. Backticks are special, and we will get to them shortly.
Length and character access
const word = "JavaScript";
console.log(word.length); // 10
console.log(word[0]); // "J"
console.log(word[4]); // "S"
console.log(word.at(-1)); // "t" last character
Positions start at 0, not 1. The first character is at index 0. The at() method accepts negative numbers to count from the end, which is neat for the last character.
Strings are immutable. You cannot change a character in place. word[0] = "j" silently does nothing. Every string method returns a new string and leaves the original alone.
Useful string methods
const text = " Learn JavaScript Step by Step ";
console.log(text.trim()); // "Learn JavaScript Step by Step"
console.log(text.toUpperCase()); // " LEARN JAVASCRIPT STEP BY STEP "
console.log(text.toLowerCase());
console.log(text.includes("Script")); // true
console.log(text.startsWith(" Learn")); // true
console.log(text.indexOf("Java")); // 8
console.log(text.trim().slice(0, 5)); // "Learn"
console.log(text.trim().replace("Step", "Stage")); // replaces first match only
console.log(text.trim().replaceAll("Step", "Stage"));
console.log("red,green,blue".split(",")); // ["red", "green", "blue"]
console.log(["a", "b", "c"].join("-")); // "a-b-c"
console.log("ha".repeat(3)); // "hahaha"
console.log("7".padStart(3, "0")); // "007"
Here is a quick guide to the ones I use most.
| Method | What it does |
|---|---|
trim() | Removes spaces from both ends |
includes(x) | True if the text contains x |
indexOf(x) | Position of x, or -1 if not found |
slice(start, end) | Cuts out a part. The end is not included |
split(sep) | Turns a string into an array |
replace / replaceAll | Swaps text |
padStart(n, ch) | Pads to a length, handy for times like 07:05 |
Notice the chaining in text.trim().slice(0, 5). Each method returns a string, so you can call the next method straight on the result.
Escape characters
If your text contains the same quote you used to open it, put a backslash in front.
const a = 'It\'s fine';
const b = "She said \"hello\"";
const c = "Line one\nLine two"; // \n is a new line
const d = "Column1\tColumn2"; // \t is a tab
const e = "C:\\Users\\Ghulam"; // \\ is a single backslash
Mixing the quote type is often simpler: "It's fine" needs no escape.
Template literals
Backticks give you template literals. They do two useful things.
First, you can put any expression inside ${ } and its value is placed in the text:
const name = "Ali";
const items = 3;
const price = 450;
console.log(`Hello, ${name}!`);
console.log(`You bought ${items} items for Rs. ${items * price}.`);
The output is Hello, Ali! and You bought 3 items for Rs. 1350.. Compare this with the old way: "You bought " + items + " items for Rs. " + (items * price) + ".". It is harder to read and easy to get wrong. I use template literals for nearly all text that has a variable in it.
Second, template literals can span several lines without any \n:
const message = `Dear ${name},
Your order is ready.
Thank you.`;
console.log(message);
The line breaks in your code become line breaks in the string. Be careful with indentation, because extra spaces at the start of lines become part of the text.
Comparing and sorting strings
Strings are compared by their character codes, so uppercase letters come before lowercase ones:
console.log("apple" === "apple"); // true
console.log("Apple" === "apple"); // false
console.log("a" < "b"); // true
console.log("Zebra" < "apple"); // true (capital Z comes before lowercase a)
For case-insensitive checks, convert both sides first: a.toLowerCase() === b.toLowerCase(). For sorting human text such as names, a.localeCompare(b) is better than <.
Common mistakes
- Expecting slice to include the end.
"hello".slice(0, 2)is"he", not"hel". - Ignoring the return value.
text.toUpperCase();on its own does nothing useful. You must store the result:text = text.toUpperCase(). - Using replace and expecting all matches.
replacechanges only the first match. UsereplaceAll. - Mixing quotes in template literals. Use backticks, not single quotes, if you want
${}to work.'Hello ${name}'prints the characters literally. - **Forgetting that
indexOfreturns -1.**if (text.indexOf("x"))is wrong. Useincludes.
Try it yourself
- Take
" hussotech.com ", remove the spaces, make it upper case and print its length. - Use a template literal to print
Ali is 25 years old and lives in Lahorefrom three variables. - Turn
"2025-06-15"into an array withsplit("-")and print the month. - Write code that pads the numbers 1 to 5 with leading zeros so they print as
001to005.
const text = " Learn JavaScript Step by Step ";
console.log(text.trim()); // "Learn JavaScript Step by Step"
console.log(text.toUpperCase()); // " LEARN JAVASCRIPT STEP BY STEP "
console.log(text.toLowerCase());
console.log(text.includes("Script")); // true
console.log(text.startsWith(" Learn")); // true
console.log(text.indexOf("Java")); // 8
console.log(text.trim().slice(0, 5)); // "Learn"
console.log(text.trim().replace("Step", "Stage")); // replaces first match only
console.log(text.trim().replaceAll("Step", "Stage"));
console.log("red,green,blue".split(",")); // ["red", "green", "blue"]
console.log(["a", "b", "c"].join("-")); // "a-b-c"
console.log("ha".repeat(3)); // "hahaha"
console.log("7".padStart(3, "0")); // "007"
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account