01 / 22
"Str"

String
Methods

Learn to index, slice, and transform strings using JavaScript's most powerful built-in methods.

JavaScript

What Is a String?

A string is a sequence of characters enclosed in quotes. Each character sits at a numbered position called an index, starting at 0.

H e l l o ! 0 1 2 3 4 5 "Hello!" has .length = 6

Accessing Characters with Bracket Notation

Use square brackets and an index to read a single character. The first character is at index 0, and the last is at index length - 1.

let word = "JavaScript"; word[0]; // "J" word[4]; // "S" word[9]; // "t" (last character) word[10]; // undefined (out of bounds)

The .length Property

Every string has a .length property that tells you how many characters it contains: including spaces and punctuation.

let msg = "Hi there!"; msg.length; // 9 msg[msg.length - 1]; // "!" (last character trick)
.length
Returns the total character count, starting from 1.
Last index
Always .length - 1 because indexing starts at 0.

Extracting with .slice()

.slice(start, end) returns a new substring from index start up to but not including index end.

J a v a S c r i p t 0 1 2 3 4 5 6 7 8 9 start: 2 end: 6 → "vaSc"
"JavaScript".slice(2, 6); // "vaSc" "JavaScript".slice(4); // "Script" (end defaults to length) "JavaScript".slice(-6); // "Script" (negative counts from end)

.slice() vs .substring()

Both extract substrings, but they differ in how they handle negative numbers and swapped arguments.

.slice() .substring()
Negative index Counts from end Treated as 0
\(start > end\) Returns "" Swaps them
Omit end Goes to end Goes to end
Preferred? ✓ Yes Legacy

Searching: .indexOf() and .includes()

.indexOf(sub)
Returns the first index where sub appears, or -1 if not found.
.includes(sub)
Returns true or false: does the string contain sub?
let s = "banana"; s.indexOf("ana"); // 1 s.indexOf("z"); // -1 s.includes("nan"); // true s.includes("Banana"); // false (case-sensitive!)

Changing Case

Two essential methods let you convert a string to all uppercase or all lowercase letters.

let name = "Ada Lovelace"; name.toUpperCase(); // "ADA LOVELACE" name.toLowerCase(); // "ada lovelace"

Replacing with .replace()

.replace(search, newValue) swaps the first match. Use .replaceAll() to swap every occurrence.

let str = "ho ho ho"; str.replace("ho", "ha"); // "ha ho ho" str.replaceAll("ho", "ha"); // "ha ha ha"
.replace()
Only the first match is replaced.
.replaceAll()
Every match is replaced.

.trim() and .split()

.trim()
Removes whitespace from both ends of a string.
.split(sep)
Breaks a string into an array at every occurrence of sep.
" Hello ".trim(); // "Hello" "a,b,c".split(","); // ["a", "b", "c"] "one two three".split(" "); // ["one", "two", "three"] "hello".split(""); // ["h", "e", "l", "l", "o"]

Building Strings with Template Literals

Use backticks ` ` and \${ } to embed expressions directly inside a string. This replaces messy concatenation with +.

let user = "Alice"; let score = 95; // Old way (concatenation): "Hi, " + user + "! Score: " + score; // Template literal: `Hi, ${user}! Score: ${score}`; // "Hi, Alice! Score: 95"

Step-by-Step: Applying String Methods

1
Identify what you need. Are you reading, searching, extracting, or transforming?
2
Pick the right method. Index access for single chars, .slice() for ranges, .indexOf() to find positions.
3
Chain if needed. Methods return new strings, so you can chain: str.trim().toLowerCase()
4
Store the result. Strings are immutable: assign the return value to a variable.

Example 1: Extract a Domain

Given an email address, extract just the domain name (after the @ sign).

let email = "student@school.edu"; // Step 1: Find the @ symbol let atIndex = email.indexOf("@"); // 7 // Step 2: Slice from after @ to end let domain = email.slice(atIndex + 1); // "school.edu"

Example 2: Capitalize First Letter

Write a function that capitalizes only the first letter of a string.

function capitalize(str) { let first = str[0].toUpperCase(); let rest = str.slice(1); return first + rest; } capitalize("hello"); // "Hello" capitalize("javaScript"); // "JavaScript"

Example 3: Count Vowels

Count how many vowels appear in a string by combining .split(), .toLowerCase(), and .includes().

function countVowels(str) { let vowels = "aeiou"; let count = 0; let chars = str.toLowerCase().split(""); for (let ch of chars) { if (vowels.includes(ch)) { count++; } } return count; } countVowels("JavaScript"); // 3

Common Mistakes

✕ Mutating the Original
Writing str.toUpperCase() without saving the result. The original str is unchanged.
✕ Off-by-One in slice()
Forgetting that the end index is exclusive. slice(0, 3) returns indices 0, 1, 2: not 3.
✕ Case Sensitivity
Using .includes("Hello") when the string contains "hello". Always normalize case first.

Method Quick Reference

Method Returns Example
.length Number "Hi".length → 2
str[i] String "Hi"[0] → "H"
.slice(s, e) String "Hello".slice(1,3) → "el"
.indexOf(sub) Number "abc".indexOf("b") → 1
.includes(sub) Boolean "abc".includes("z") → false
.toUpperCase() String "hi".toUpperCase() → "HI"
.replace(a, b) String "ab".replace("a","x") → "xb"
.trim() String " hi ".trim() → "hi"
.split(sep) Array "a-b".split("-") → ["a","b"]

Question 1 of 5

What does "JavaScript".slice(4, 10) return?

Question 2 of 5

What does "banana".indexOf("ana") return?

Question 3 of 5

Which expression correctly gets the last character of a string stored in variable s?

Question 5 of 5

What does "hello world".split(" ").length evaluate to?