Strings & String Methods

📖 Concept

Strings are sequences of characters used to represent text. They are immutable — string methods return NEW strings without modifying the original.

Strings can be created with single quotes (''), double quotes (""), or backticks (\``) for template literals.

Key methods: .length, .toUpperCase(), .toLowerCase(), .trim(), .slice(), .split(), .includes(), .indexOf(), .replace(), .replaceAll(), .startsWith(), .endsWith(), .padStart(), .repeat(), .at()

🏠 Real-world analogy: Strings are like printed text on paper — you can't erase a letter, but you can photocopy the page with changes.

💻 Code Example

codeTap to expand ⛶
1const str = " Hello, JavaScript World! ";
2
3// Basics
4console.log(str.length); // 29
5console.log(str.trim()); // "Hello, JavaScript World!"
6console.log(str.toUpperCase()); // " HELLO, JAVASCRIPT WORLD! "
7
8// Searching
9console.log(str.includes("Java")); // true
10console.log(str.indexOf("World")); // 22
11console.log(str.startsWith(" He")); // true
12
13// Extracting
14console.log(str.slice(8, 18)); // "JavaScript"
15console.log(str.at(-3)); // "! " → "d" (after trim)
16
17// Modifying (returns new string)
18console.log(str.replace("World", "Universe"));
19console.log("ha".repeat(3)); // "hahaha"
20
21// Splitting
22const csv = "apple,banana,cherry";
23const fruits = csv.split(","); // ["apple", "banana", "cherry"]
24
25// Padding (useful for formatting)
26const num = "5";
27console.log(num.padStart(3, "0")); // "005"
28
29// Template literals
30const name = "Alice";
31const greeting = `Hello, ${name}! You have ${2 + 3} messages.`;

🏋️ Practice Exercise

Mini Exercise:

  1. Write a function that takes a full name and returns initials (e.g., "John Doe" → "J.D.")
  2. Write a function that censors a word in a sentence (replaces with ****)
  3. Write a function to convert "hello-world-foo" to camelCase "helloWorldFoo"
  4. Reverse a string without using .reverse()

⚠️ Common Mistakes

  • Forgetting strings are immutable — str.toUpperCase() returns a new string, doesn't modify str

  • Confusing slice() with splice()slice is for strings/arrays (non-destructive), splice is array-only (destructive)

  • Using indexOf and checking if(str.indexOf('x')) — returns 0 for index 0, which is falsy! Use !== -1 or includes()

  • Not knowing that + operator with strings causes concatenation instead of addition

  • Forgetting that split('') splits into individual characters, while split() returns array with entire string

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Strings & String Methods. Login to unlock this feature.