JavaScript Strings

JavaScript Strings

JavaScript Strings — What They Are and How to Use Them | TipsInLearning
JavaScript Fundamentals

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.

12 min read
Beginner
Essential
Strings are one of the first things that actually feels useful when learning JavaScript. The moment you understand how to manipulate text — combine names, format messages, check what a user typed — the language starts feeling practical rather than abstract. That's what this lesson is for.

What You'll Be Able to Do After This Lesson

Create strings three different ways and know when to use each
Access individual characters using their index position
Use the most important string methods (slice, indexOf, includes, replace)
Write template literals instead of messy string concatenation
Understand why your string method isn't changing your original variable
Avoid the 3 mistakes beginners make with strings almost every time

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.

One thing to understand early: strings are immutable in JavaScript. That means once a string is created, you can't change individual characters inside it. You can only create new strings based on the old one. This trips up a lot of beginners — we'll cover it properly in the Immutability section below.

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:

JavaScript
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
Which should you use? Most modern JavaScript developers default to single quotes. What actually matters is consistency — pick one and use it throughout your project. Mixing them randomly makes code messy to read.

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.

JavaScript
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.

JavaScript
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
Note: .length is a property, not a method — so no brackets at the end. Writing word.length() will throw an error. It's just word.length.

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:

JavaScript
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.

MethodWhat it doesExampleResult
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.

JavaScript — slice() in practice
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

JavaScript — includes, indexOf, replace
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.

JavaScript — Template literal basics
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:

JavaScript — Immutability in action
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
The rule: String methods always return a new value. They never modify the original. If you want the result, either store it in a new variable or reassign the original variable.

Common Mistakes With Strings

Calling a method and not saving the result
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().
Getting confused by zero-based indexing
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.
Forgetting that string comparisons are case-sensitive
"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

1
Use template literals for string buildingAny time you're combining variables with text, template literals are cleaner than + concatenation. They're especially helpful with multiple variables or multi-line strings.
2
Use includes() instead of indexOf() for existence checkstext.includes('word') is clearer than text.indexOf('word') !== -1. Both work, but includes() tells you what it's doing without mental translation.
3
Prefer slice() over substring()slice() handles negative indices, which is useful. substring() doesn't. Just use slice() consistently and you won't need to think about it.
4
Always store or reassign method resultsString methods don't change the original. If you need the result, assign it: let result = str.toUpperCase(). Calling the method without storing the result does nothing.
5
Normalise case before comparingWhen comparing strings from user input, convert both sides to lowercase first. Users type things in all kinds of ways — case-insensitive comparison prevents unnecessary mismatches.
Quick Summary
1Strings store text. Create them with single quotes, double quotes, or backticks — each has its use case.
2Strings are zero-indexed — first character at position 0, last at length - 1.
3Template literals (`${variable}`) are the modern way to build strings with variables. Use them.
4Strings are immutable — methods return new strings. Always store the result or nothing changes.
5Use includes() to check existence, slice() to extract, replace() to swap text.
6String comparisons are case-sensitive. Normalise with toLowerCase() before comparing user input.

Questions About JavaScript Strings

The questions that come up most when beginners start working with strings:

Why is my string method not changing my variable?
Because strings are immutable — methods return a new string, they don't modify the original. So myStr.toUpperCase() doesn't change myStr, it returns a new uppercase string that you need to store. Fix it by either storing the result in a new variable (let upper = myStr.toUpperCase()) or reassigning the original (myStr = myStr.toUpperCase()). This is the number one string mistake beginners make.
Should I use single quotes or double quotes?
There's no difference — they're functionally identical. Most modern JavaScript developers use single quotes by default. The only time you need to switch is when your string itself contains one of them (use double quotes for strings with apostrophes like "It's", use single quotes for strings with double quotes). What matters most is being consistent within a project. Mixing styles randomly for no reason makes code harder to read.
When should I use template literals vs regular quotes?
Use template literals any time you're building a string that includes variable values. `Hello, ${name}!` is far cleaner than "Hello, " + name + "!", especially when you have multiple variables. Use regular quotes for simple static strings with no variables — let colour = 'blue' — where there's nothing to interpolate and backticks would just add visual noise.
What's the difference between slice() and substring()?
Both extract a portion of a string. The practical difference: slice() accepts negative indices (so text.slice(-3) gives you the last 3 characters), while substring() treats negative values as 0. Just use slice() — it's more flexible. The only reason to know about substring() is that you'll encounter it in older codebases.
How do I check if a string contains another string?
Use includes() — it returns true or false directly: text.includes('hello'). You may see older code using indexOf() !== -1 which does the same thing but is less readable. Stick with includes() for new code. Remember it's case-sensitive — "Hello".includes("hello") returns false because of the capital H.

Post a Comment