String
Methods
Learn to index, slice, and transform strings using JavaScript's most powerful built-in methods.
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.
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.
The .length Property
Every string has a .length property that tells you how many characters it contains: including spaces and punctuation.
Extracting with .slice()
.slice(start, end) returns a new substring from index start up to but not including index 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()
Changing Case
Two essential methods let you convert a string to all uppercase or all lowercase letters.
Replacing with .replace()
.replace(search, newValue) swaps the first match. Use .replaceAll() to swap every occurrence.
.trim() and .split()
Building Strings with Template Literals
Use backticks ` ` and \${ } to embed expressions directly inside a string. This replaces messy concatenation with +.
Step-by-Step: Applying String Methods
Example 1: Extract a Domain
Given an email address, extract just the domain name (after the @ sign).
Example 2: Capitalize First Letter
Write a function that capitalizes only the first letter of a string.
Example 3: Count Vowels
Count how many vowels appear in a string by combining .split(), .toLowerCase(), and .includes().
Common Mistakes
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 4 of 5
What does "ho ho ho".replace("ho", "ha") return?
Question 5 of 5
What does "hello world".split(" ").length evaluate to?