JavaScript Strings
Strings are how JavaScript handles text — and you'll use them constantly. This lesson covers everything from the basics of creating strings to the methods you'll reach for every single day as a developer.
What You'll Be Able to Do After This Lesson
What Are Strings?
A string is any piece of text in your code. A name, a sentence, an email address, a URL, a single letter — if it's text, it's a string. In JavaScript, you create a string by wrapping text in quotes.
The name "string" comes from the idea of characters strung together in a sequence. That's a useful way to think about them — not one thing, but a chain of individual characters that happen to be stored together.
Creating Strings — 3 Ways
JavaScript gives you three ways to create a string. They're not just different syntax — each has a specific situation where it's the right choice.
Single Quotes and Double Quotes
These are functionally identical. The only time the choice matters is when your string contains one of them:
let name = 'John'; // single quotes let city = "London"; // double quotes — same result // Use double quotes when your string contains an apostrophe let sentence = "It's a great day"; // works fine let broken = 'It's a great day'; // BROKEN — JavaScript thinks string ends at It // Use single quotes when your string contains double quotes let quote = 'He said "hello"'; // works fine
Template Literals (Backticks)
Template literals use backtick characters ( ` ) instead of quotes. They look a bit odd at first but they're genuinely better for most situations — especially when you need to include variable values inside a string.
let user = 'Alice'; // Old way — concatenation with + signs let msg1 = 'Hello, ' + user + '! Welcome back.'; // New way — template literals with ${} let msg2 = `Hello, ${user}! Welcome back.`; // Both produce: "Hello, Alice! Welcome back." // But msg2 is much easier to read and maintain
String Length
The .length property tells you how many characters are in a string. It counts everything — letters, spaces, punctuation, even emoji.
let word = 'Hello'; console.log(word.length); // 5 let sentence = 'JavaScript is fun!'; console.log(sentence.length); // 18 — spaces count too let empty = ''; console.log(empty.length); // 0
Accessing Individual Characters
Strings are zero-indexed — the first character is at position 0, not position 1. This is one of the things that confuses beginners most often, so let's make it concrete:
let text = 'Hello'; // H e l l o // index: 0 1 2 3 4 // Bracket notation (modern, preferred) console.log(text[0]); // 'H' console.log(text[4]); // 'o' console.log(text[10]); // undefined (out of range) // charAt() method (older, same result) console.log(text.charAt(0)); // 'H' console.log(text.charAt(10)); // '' (empty string, not undefined)
String Methods You'll Actually Use
JavaScript has dozens of string methods. These are the ones you'll use regularly — not a complete reference, but the ones worth learning properly now.
| Method | What it does | Example | Result |
|---|---|---|---|
| toUpperCase() | All letters uppercase | "hello".toUpperCase() | "HELLO" |
| toLowerCase() | All letters lowercase | "HELLO".toLowerCase() | "hello" |
| trim() | Remove leading/trailing spaces | " hi ".trim() | "hi" |
| includes() | Check if text is inside | "Hello".includes("ell") | true |
| startsWith() | Check what string starts with | "Hello".startsWith("He") | true |
| indexOf() | Find position of text (-1 if not found) | "Hello".indexOf("l") | 2 |
| slice() | Extract a section | "Hello".slice(1, 4) | "ell" |
| replace() | Replace first match | "Hi Hi".replace("Hi","Hey") | "Hey Hi" |
| replaceAll() | Replace every match | "Hi Hi".replaceAll("Hi","Hey") | "Hey Hey" |
| split() | Split into array | "a,b,c".split(",") | ["a","b","c"] |
Extracting Parts of a String — slice() vs substring()
This is one people always ask about. Here's the honest answer: use slice(). It does everything substring() does, plus it accepts negative indices. The only reason to know about substring() is that you'll see it in older code.
let text = 'Hello World'; // slice(start, end) — end index is NOT included console.log(text.slice(0, 5)); // 'Hello' console.log(text.slice(6)); // 'World' (from index 6 to end) console.log(text.slice(-5)); // 'World' (last 5 characters) // Practical use — get file extension let filename = 'photo.jpg'; let extension = filename.slice(-3); // 'jpg'
Searching Inside Strings
let email = 'user@tipsinlearning.com'; // includes() — just want to know if it's there console.log(email.includes('@')); // true console.log(email.includes('gmail')); // false // indexOf() — want to know WHERE it is (-1 means not found) console.log(email.indexOf('@')); // 4 console.log(email.indexOf('x')); // -1 (not found) // replace() — swap out text let message = 'Hello World World'; console.log(message.replace('World', 'JS')); // 'Hello JS World' (first only) console.log(message.replaceAll('World', 'JS')); // 'Hello JS JS' (all)
Template Literals — The Modern Way
Template literals were added to JavaScript in 2015 and they genuinely make string handling easier. If you're writing new JavaScript code, you should be using them by default for anything that involves variables.
let name = 'Sarah'; let score = 94; let subject = 'JavaScript'; // Concatenation — readable but gets messy fast let msg1 = name + ' scored ' + score + '% in ' + subject; // Template literal — clean and easy to read let msg2 = `${name} scored ${score}% in ${subject}`; // You can also run expressions inside ${} let a = 10, b = 5; console.log(`${a} divided by ${b} = ${a/b}`); // "10 divided by 5 = 2" // Multi-line strings — no more \n everywhere let card = `Name: ${name} Score: ${score}% Subject: ${subject}`;
Strings Are Immutable — This Confuses Everyone
Immutable means it can't be changed in place. When you call a string method like toUpperCase(), it doesn't change your original string — it returns a brand new string. Your original is untouched.
This catches beginners out constantly. You call a method, expect the variable to change, then check it and it's the same as before. Here's why:
let original = 'hello'; // This does NOT change original original.toUpperCase(); console.log(original); // still 'hello' — unchanged // To actually use the result, store it let upper = original.toUpperCase(); console.log(upper); // 'HELLO' // Or reassign the variable if you want to update it original = original.toUpperCase(); console.log(original); // 'HELLO' — now updated
Common Mistakes With Strings
myString.trim() returns a trimmed string but doesn't change myString. If you don't store the result in a variable, the trimmed value is just thrown away. Always do: let clean = myString.trim() or myString = myString.trim().
The first character is at index 0, not index 1. So in the string "Hello", H is at index 0 and o is at index 4. Off-by-one errors are extremely common here — always pause and count from zero, not one.
"Hello" === "hello" is false. If you're comparing strings that might have different capitalisation — user input for example — always convert both to the same case first: input.toLowerCase() === "hello".
Best Practices
Questions About JavaScript Strings
The questions that come up most when beginners start working with strings: