🌱BeginnerJavaScript Fundamentals
String Methods
The essential built-in methods for searching, transforming, and slicing strings in JavaScript.
Overview
Strings in JavaScript are immutable sequences of characters. Every string value is automatically wrapped in a `String` object, giving you access to dozens of built-in methods via the dot operator. These methods never modify the original string they always return a new value.
Knowing the right string method saves you from writing tedious manual loops. Need to check if a URL contains "https"? Use `.includes()`. Need to extract a filename from a path? Use `.slice()` or `.split()`. Need to normalise user input? Chain `.trim().toLowerCase()`.
Strings are also zero-indexed like arrays `"hello"[0]` is `"h"`. You can measure their length with `.length`. Individual characters can be accessed with `.charAt(i)` or bracket notation `str[i]`.
Key Points
- •Strings are immutable all methods return new strings, never modifying the original
- •`.length` number of characters; `str[i]` or `.charAt(i)` character at position i
- •`.toUpperCase()` / `.toLowerCase()` case conversion
- •`.trim()` remove leading/trailing whitespace; `.trimStart()` / `.trimEnd()` for one side
- •`.includes(sub)` boolean; `.startsWith(sub)` / `.endsWith(sub)` position-specific checks
- •`.indexOf(sub)` first occurrence index (−1 if not found); `.lastIndexOf(sub)` from the end
- •`.slice(start, end)` extract substring from start up to (not including) end
- •`.split(sep)` split string into array; `[].join(sep)` join array back into string
- •`.replace(search, replacement)` first match; `.replaceAll()` all matches
- •`.padStart(len, char)` / `.padEnd()` pad to target length
Examples
Case, trim, and length
const input = " Hello, World! ";
console.log(input.length); // 18
console.log(input.trim()); // "Hello, World!"
console.log(input.trim().toUpperCase()); // "HELLO, WORLD!"
console.log(input.trim().toLowerCase()); // "hello, world!"
const email = " User@Example.COM ";
const normalised = email.trim().toLowerCase();
console.log(normalised); // "user@example.com"Searching inside strings
const url = "https://blog.kriativity.in/javascript/beginner/intro";
console.log(url.includes("javascript")); // true
console.log(url.startsWith("https")); // true
console.log(url.endsWith("intro")); // true
console.log(url.indexOf("javascript")); // 30 (first position)
console.log(url.indexOf("python")); // -1 (not found)
// Check if an email looks valid
const email = "user@example.com";
console.log(email.includes("@") && email.includes(".")); // trueSlicing and splitting
const date = "2024-06-15";
// slice(start, end) end is exclusive
console.log(date.slice(0, 4)); // "2024" (year)
console.log(date.slice(5, 7)); // "06" (month)
console.log(date.slice(8)); // "15" (day, no end = go to end)
console.log(date.slice(-2)); // "15" (negative = from end)
// split and join
const parts = date.split("-"); // ["2024", "06", "15"]
console.log(parts);
console.log(parts.join("/")); // "2024/06/15"
const sentence = "one two three";
const words = sentence.split(" "); // ["one", "two", "three"]
console.log(words.length); // 3Replace, repeat, and pad
// replace first match only
let msg = "hello world, hello JS";
console.log(msg.replace("hello", "hi")); // "hi world, hello JS"
console.log(msg.replaceAll("hello", "hi")); // "hi world, hi JS"
// Replace with regex remove all non-digits
const phone = "(555) 123-4567";
console.log(phone.replace(/\D/g, "")); // "5551234567"
// padStart format numbers with leading zeros
const hour = "9";
console.log(hour.padStart(2, "0")); // "09"
console.log("5".padStart(3, "0")); // "005"
// repeat
console.log("ab".repeat(3)); // "ababab"Common Mistakes
- Modifying the return value strings are immutable; you must reassign: `str = str.trim()`, not just `str.trim()`
- Using `.indexOf()` and forgetting it returns −1 (not null/undefined) when not found if (str.indexOf("x")) is truthy even when indexOf returns 0
- Confusing `.slice(start, end)` with `.substring(start, end)` slice accepts negative indices, substring does not; prefer slice
Note
Chain methods for clean transformations: `input.trim().toLowerCase().replace(/\s+/g, "-")` turns " Hello World " into "hello-world" in one expression.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4