Small methods you will use all the time. None of them change the original string. They return a new one.
Changing case
const text = "Hello World";
console.log(text.toUpperCase()); // → HELLO WORLD
console.log(text.toLowerCase()); // → hello world
console.log(text); // → Hello World
A common use: compare text without caring about case.
const answer = " YES ";
console.log(answer.trim().toLowerCase() === "yes"); // → true
trim
trim() removes spaces, tabs and line breaks from both ends. trimStart() and trimEnd() do one side.
const input = " maya@example.com \n";
console.log(`[${input.trim()}]`); // → [maya@example.com]
console.log(`[${input.trimStart()}]`);
console.log(`[${input.trimEnd()}]`);
Always trim text from form fields before you check it. A field with only spaces looks empty to the user but is not an empty string.
padStart and padEnd
These add characters until the string reaches a length you choose. They are perfect for numbers that need leading zeros, and for aligning text.
const minutes = 5;
const seconds = 7;
console.log(`${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`); // → 05:07
console.log("Name".padEnd(10, ".") + "Maya"); // → Name......Maya
console.log("42".padStart(6)); // → 42
Only strings can be padded, so convert numbers with String() or .toString() first.
repeat
console.log("ab".repeat(3)); // → ababab
console.log("-".repeat(10)); // → ----------
Methods can be chained
Because each method returns a string, you can call another straight away:
const slug = " My First Blog Post ".trim().toLowerCase().replaceAll(" ", "-");
console.log(slug); // → my-first-blog-post
That final replaceAll() is in the next lesson: replace, replaceAll and split.