In short
JavaScript strings store text. In this lesson you will learn how to create strings, use template literals, read single characters and use the most useful string methods.
JavaScript strings store text. In this lesson you will learn how to create strings, use template literals, read single characters and use the most useful string methods.
How to create a string: single quotes, double quotes and backticks
A string is a piece of text: a name, a message, an email address, even a single letter. You create a string by putting text inside quotes. JavaScript accepts three kinds:
const firstName = 'Lena'; // single quotes
const lastName = "Fischer"; // double quotes
const greeting = `Hi, I'm Lena!`; // backticks (template literal)
console.log(firstName, lastName);
// Output: Lena Fischer
console.log(greeting);
// Output: Hi, I'm Lena!
Single and double quotes work exactly the same. Pick one style and use it everywhere; many projects use single quotes. The third kind uses backticks, the slanted quote character usually found on the key above Tab. Strings in backticks are called template literals, and they have special powers.
Template literals in JavaScript: putting variables inside text
Before template literals, you had to join strings with the + sign. This is called concatenation, and it gets messy fast. With a template literal, you can put any variable or calculation straight into the text using ${ }.
const customer = 'Lena';
const items = 3;
const price = 12.5;
// Old way: concatenation with +
const oldMessage = 'Hi ' + customer + ', you have ' + items + ' items in your cart.';
// Modern way: template literal
const message = `Hi ${customer}, you have ${items} items in your cart.`;
const total = `Total: $${items * price}`;
console.log(oldMessage);
// Output: Hi Lena, you have 3 items in your cart.
console.log(message);
// Output: Hi Lena, you have 3 items in your cart.
console.log(total);
// Output: Total: $37.5
Inside ${ } you can write any JavaScript expression, even math like items * price. In $${...}, the first $ is just a normal dollar sign, and the second starts the placeholder. Template literals can also span several lines, which is great for longer messages.
String length and indexing: reading single characters
Every string has a length property that tells you how many characters it contains. Spaces and punctuation count too.
Each character also has a position number called an index. Indexes start at 0, not 1. So the first character is at index 0, the second at index 1, and the last one at length - 1.
const word = 'JavaScript';
console.log(word.length); // Output: 10
console.log(word[0]); // Output: J
console.log(word[4]); // Output: S
console.log(word[word.length - 1]); // Output: t
console.log(word.at(-1)); // Output: t
console.log(word[20]); // Output: undefined
word.at(-1) is a modern, easier way to get the last character: negative numbers count from the end. Asking for an index that doesn't exist gives undefined, not an error.
Common mistake: Expecting the first character to be at index 1. In JavaScript (and most programming languages), counting starts at 0.
Common JavaScript string methods
A method is an action that a value can do. You call it with a dot, the method name and brackets: text.toUpperCase(). Strings come with many methods. These are the ones you'll use most:
| Method | What it does | Example | Result |
|---|---|---|---|
toUpperCase() | All capitals | 'hi'.toUpperCase() | 'HI' |
toLowerCase() | All lowercase | 'HI'.toLowerCase() | 'hi' |
trim() | Removes spaces at the start and end | ' hi '.trim() | 'hi' |
includes(x) | Does it contain x? | 'hello'.includes('ell') | true |
startsWith(x) | Does it begin with x? | 'hello'.startsWith('he') | true |
endsWith(x) | Does it end with x? | 'photo.png'.endsWith('.png') | true |
slice(start, end) | Cuts out a part (end not included) | 'hello'.slice(1, 4) | 'ell' |
replace(a, b) | Replaces the first a with b | 'a-b-c'.replace('-', '+') | 'a+b-c' |
replaceAll(a, b) | Replaces every a with b | 'a-b-c'.replaceAll('-', '+') | 'a+b+c' |
split(x) | Breaks into a list at each x | 'a,b,c'.split(',') | ['a', 'b', 'c'] |
padStart(n, x) | Adds x at the start until length n | '7'.padStart(3, '0') | '007' |
Here they are in a realistic example: cleaning up what a user typed into a signup form.
const rawEmail = ' Lena.Fischer@Example.COM ';
const email = rawEmail.trim().toLowerCase();
console.log(email);
// Output: lena.fischer@example.com
console.log(email.includes('@'));
// Output: true
console.log(email.endsWith('.com'));
// Output: true
const username = email.slice(0, email.indexOf('@'));
console.log(username);
// Output: lena.fischer
const tags = 'html, css, javascript'.split(', ');
console.log(tags);
// Output: ['html', 'css', 'javascript']
const orderNumber = String(42).padStart(6, '0');
console.log(`Order #${orderNumber}`);
// Output: Order #000042
const slug = 'My First Blog Post'.toLowerCase().replaceAll(' ', '-');
console.log(slug);
// Output: my-first-blog-post
What's happening:
trim().toLowerCase()chains two methods: first remove extra spaces, then make it lowercase.indexOf('@')gives the position of@(here 12), soslice(0, 12)takes everything before it.split(', ')turns one string into an array of three strings.padStart(6, '0')adds zeros in front until the text is 6 characters long.String(42)turns the number into a string first.replaceAll(' ', '-')turns a title into a URL-friendly "slug".
Most string methods are case-sensitive: 'Hello'.includes('hello') is false. That's why it's common to use toLowerCase() before comparing.
Escaping special characters in strings
What if your text contains the same quote you used to create the string? 'It's sunny' breaks, because JavaScript thinks the string ends after It. You have two fixes: use a different kind of quote, or escape the character with a backslash \.
const a = "It's sunny"; // use double quotes outside
const b = 'It\'s sunny'; // or escape the quote with \
const path = 'C:\\Users\\Lena'; // \\ means one real backslash
const lines = 'Line one\nLine two'; // \n means "new line"
console.log(b);
// Output: It's sunny
console.log(path);
// Output: C:\Users\Lena
console.log(lines);
// Output:
// Line one
// Line two
The most common escape sequences are \', \", \\ (a backslash), \n (a new line) and \t (a tab).
Strings are immutable
Immutable means "cannot be changed". Once a string is created, you can't change one of its characters. String methods never change the original; they always give you back a new string.
let city = 'paris';
city[0] = 'P';
console.log(city);
// Output: paris (nothing changed)
city.toUpperCase();
console.log(city);
// Output: paris (still unchanged)
city = city[0].toUpperCase() + city.slice(1);
console.log(city);
// Output: Paris
To "change" a string, you create a new one and store it, like on the last line.
Tip: Calling a method like
name.trim()on its own line does nothing useful. Always save the result:name = name.trim();orconst cleanName = name.trim();.
Practice exercise
Write a small "name badge" program. Start with const input = ' maria garcia ';. Clean it with trim(), then make the first letter of each name a capital so it says Maria Garcia. Finally log a template literal like Hello, Maria Garcia! Your name has 12 characters.
Hint: use split(' ') to get the two names, then for each name use name[0].toUpperCase() + name.slice(1). Join them back with a space.
Key takeaways
- Strings are text inside single quotes, double quotes or backticks.
- Template literals with backticks let you insert values with
${ }. - Indexes start at 0;
lengthgives the number of characters, andat(-1)gives the last one. - Methods like
trim,toLowerCase,includes,slice,replaceAllandsplitreturn new strings or values. - Strings are immutable: save the result of a method in a variable.