Lesson 4 of 34 · Fundamentals
JavaScript Strings and Template Literals
Names, messages, chat logs, quest descriptions: text is everywhere in software. In JavaScript, text lives in strings, and strings come with a toolbox of built-in methods for slicing, searching and formatting them.
You'll also meet template literals, the modern way to build strings that mix text and values.
Strings, length and indexes
A string is a sequence of characters. Its length property tells you how many characters it has, and you can read single characters by index, counting from 0:
const realm = "Scriptoria";
console.log(realm.length); // 10
console.log(realm[0]); // S
console.log(realm[3]); // i
console.log(realm.at(-1)); // a (negative indexes count from the end)
Strings are immutable: you can't change a character in place. Every string method returns a new string and leaves the original untouched.
Joining strings: + versus template literals
You can glue strings together with +:
const name = "Ada";
const level = 7;
console.log("Hero " + name + " is level " + level + "."); // Hero Ada is level 7.
It works, but the quotes and plus signs get messy fast. Template literals use backticks and let you drop any expression into ${...}:
console.log(`Hero ${name} is level ${level}.`); // Hero Ada is level 7.
console.log(`Next level: ${level + 1}`); // Next level: 8
Template literals can also span several lines:
const banner = `Welcome, ${name}!
Your quest begins now.`;
Essential string methods
const raw = " Dragon Slayer ";
console.log(raw.trim()); // Dragon Slayer
console.log("hello".toUpperCase()); // HELLO
console.log("HeLLo".toLowerCase()); // hello
console.log("fireball".includes("fire")); // true
console.log("fireball".startsWith("fi")); // true
console.log("fireball".endsWith("ball")); // true
console.log("fireball".indexOf("ball")); // 4 (-1 when not found)
console.log("ha".repeat(3)); // hahaha
console.log("7".padStart(3, "0")); // 007
console.log("a-b-c".replaceAll("-", "+")); // a+b+c
slice(start, end) copies part of a string. The end index is not included, and leaving it out means "until the end":
const spell = "fireball";
console.log(spell.slice(0, 4)); // fire
console.log(spell.slice(4)); // ball
console.log(spell.slice(-3)); // all
A handy property of slice: it never fails. On an empty string, "".slice(0, 1) is simply "", while ""[0] is undefined.
Chaining methods
Because every method returns a new string, you can call another method on the result:
const input = " gANDALF ";
const clean = input.trim().toLowerCase();
console.log(clean); // gandalf
Common mistakes
- Using quotes instead of backticks.
"Hi ${name}"prints the${name}literally. Only backticks interpolate. - Forgetting the parentheses.
name.toUpperCasewithout()is the function itself, not the result. - Expecting the original to change.
name.trim();on its own line does nothing useful. Store or return the result:const clean = name.trim();. - Off-by-one with
slice. The end index is excluded:"abc".slice(0, 2)is"ab".
Assignment
Complete three functions:
greet(name)returns"Welcome to Scriptoria, <name>!", with any spaces around the name removed. Example:greet(" Ada ")returns"Welcome to Scriptoria, Ada!".capitalize(word)returns the word with its first letter in upper case and the rest in lower case. Example:capitalize("wIZARD")returns"Wizard". An empty string stays empty.progressBar(done, total)returns a text progress bar:done#characters followed bytotal - done-characters, inside square brackets. Example:progressBar(3, 5)returns"[###--]".
Strings and formatting in other languages
- Python Strings and f-Strings · Python
- Go Strings and fmt.Sprintf Formatting · Go
- Java Strings and String Methods · Java
- C# Strings and String Interpolation · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .