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
1const str = " Hello, JavaScript World! ";23// Basics4console.log(str.length); // 295console.log(str.trim()); // "Hello, JavaScript World!"6console.log(str.toUpperCase()); // " HELLO, JAVASCRIPT WORLD! "78// Searching9console.log(str.includes("Java")); // true10console.log(str.indexOf("World")); // 2211console.log(str.startsWith(" He")); // true1213// Extracting14console.log(str.slice(8, 18)); // "JavaScript"15console.log(str.at(-3)); // "! " → "d" (after trim)1617// Modifying (returns new string)18console.log(str.replace("World", "Universe"));19console.log("ha".repeat(3)); // "hahaha"2021// Splitting22const csv = "apple,banana,cherry";23const fruits = csv.split(","); // ["apple", "banana", "cherry"]2425// Padding (useful for formatting)26const num = "5";27console.log(num.padStart(3, "0")); // "005"2829// Template literals30const name = "Alice";31const greeting = `Hello, ${name}! You have ${2 + 3} messages.`;
🏋️ Practice Exercise
Mini Exercise:
- Write a function that takes a full name and returns initials (e.g., "John Doe" → "J.D.")
- Write a function that censors a word in a sentence (replaces with ****)
- Write a function to convert "hello-world-foo" to camelCase "helloWorldFoo"
- Reverse a string without using
.reverse()
⚠️ Common Mistakes
Forgetting strings are immutable —
str.toUpperCase()returns a new string, doesn't modifystrConfusing
slice()withsplice()—sliceis for strings/arrays (non-destructive),spliceis array-only (destructive)Using
indexOfand checkingif(str.indexOf('x'))— returns 0 for index 0, which is falsy! Use!== -1orincludes()Not knowing that
+operator with strings causes concatenation instead of additionForgetting that
split('')splits into individual characters, whilesplit()returns array with entire string
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Strings & String Methods. Login to unlock this feature.