JavaScript ยท Chapter 17 of 55
JavaScript String Methods
JavaScript strings have many built-in methods for searching, extracting, and transforming text: `slice()`, `toUpperCase()`, `trim()`, `replace()`, `includes()`, and more.
Because strings are immutable, all these methods return a brand new string instead of modifying the original.
Searching and extracting
`indexOf()` and `includes()` search for substrings. `slice(start, end)` extracts a portion of the string.
Transforming
`toUpperCase()`, `toLowerCase()`, `trim()`, and `replace()` return transformed copies of the string.
Example 1 (javascript)
let s = "Hello World";
console.log(s.toUpperCase());
console.log(s.slice(0, 5));Output
HELLO WORLD
Helloslice extracts a substring; toUpperCase transforms case.
Example 2 (javascript)
let s = "Hello World";
console.log(s.includes("World"));
console.log(s.replace("World", "JS"));Output
true
Hello JSincludes checks for a substring; replace swaps text.
Key points
- String methods return new strings, leaving the original unchanged.
- `slice(start, end)` extracts a substring (end exclusive).
- `includes()` checks for substring presence; returns a boolean.
- `replace()` swaps the first match; `replaceAll()` swaps all matches.
๐ก Note: Use `replaceAll()` (ES2021+) when you need to replace every occurrence, not just the first.
