Sub topic 7
Changing Case, Trimming, and Padding
This chapter assumes you know that string methods return new strings and leave the original alone, as covered in the chapter on immutability. You should also be comfortable calling methods and logging results in a browser console or Node.js.
The methods in this chapter clean up and format text. You use them to normalize user input, tidy data before comparing it, and line up output in fixed-width columns.
Changing Case
toUpperCase() and toLowerCase() return a copy of the string with every letter converted. Characters that are not letters pass through unchanged.
const name = "Ada Lovelace";
console.log(name.toUpperCase()); // ADA LOVELACE
console.log(name.toLowerCase()); // ada lovelace
console.log(name); // Ada Lovelace (unchanged)
const a = "[email protected]";
const b = "[email protected]";
console.log(a.toLowerCase() === b.toLowerCase()); // trueSome languages have case rules that differ from English. The locale-aware versions take a language tag:
console.log("I".toLowerCase()); // i
console.log("I".toLocaleLowerCase("tr")); // ı (Turkish dotless i)
console.log("ß".toUpperCase()); // SS
console.log("ß".toUpperCase().length); // 2Trimming Whitespace
trim() removes whitespace from both ends of a string. trimStart() removes it only from the start, and trimEnd() only from the end. "Whitespace" here means spaces, tabs, line terminators such as \n, and Unicode spaces such as the non-breaking space \u00A0. Whitespace inside the string is left alone.
const raw = "\t hello world \n";
console.log(JSON.stringify(raw.trim())); // "hello world"
console.log(JSON.stringify(raw.trimStart())); // "hello world \n"
console.log(JSON.stringify(raw.trimEnd())); // "\t hello world"
console.log("\u00A0x\u00A0".trim().length); // 1A common mistake is calling trim() and ignoring the result. Because strings are immutable, input.trim(); by itself does nothing useful. You have to write input = input.trim();.
Padding
padStart(targetLength, padString) and padEnd(targetLength, padString) add characters until the string reaches targetLength. The pad string defaults to a single space. If the pad string doesn't fit evenly into the space left, it is cut short. If the string is already at least targetLength long, it comes back unchanged and is never truncated.
console.log("5".padStart(3, "0")); // 005
console.log("x".padStart(6, "ab")); // ababax
console.log("7".padEnd(5, "ab")); // 7abab
console.log("abcdef".padStart(3)); // abcdef
const rows = [["Apples", 3], ["Kiwis", 12]];
for (const [item, qty] of rows) {
console.log(item.padEnd(8, ".") + String(qty).padStart(4));
}
// Apples.... 3
// Kiwis..... 12Numbers have no padStart method, so convert them first with String(qty).
Repeating
repeat(count) returns the string joined to itself count times. A count of 0 returns "". A negative count or Infinity throws a RangeError.
console.log("-".repeat(10)); // ----------
console.log("ab".repeat(0)); // "" (empty)
try {
"ab".repeat(-1);
} catch (e) {
console.log(e.name); // RangeError
}Choosing a Method
| Task | Method |
|---|---|
| Compare text without caring about case | `toLowerCase()` on both sides |
| Convert case following a language's rules | `toLocaleUpperCase(locale)` / `toLocaleLowerCase(locale)` |
| Clean up form input | `trim()` |
| Remove trailing newlines only | `trimEnd()` |
| Add leading zeros or right-align text | `padStart()` |
| Left-align text in a column | `padEnd()` |
| Draw separator lines | `repeat()` |
Exercise
Write a function formatId(n) that turns a number into a string at least 6 characters long, with leading zeros, prefixed by "ID-". For example, formatId(42) returns "ID-000042". What does your function return for 1234567, and why?
Show answer
function formatId(n) { return "ID-" + String(n).padStart(6, "0"); } For 1234567 it returns "ID-1234567". padStart never shortens a string, so a value already longer than the target length comes back unchanged.
Exercise
A user enters " Admin\n" in a form. Write one expression that checks whether the input means "admin", ignoring surrounding whitespace and case.
Show answer
input.trim().toLowerCase() === "admin". trim removes the spaces and the newline, and toLowerCase makes the comparison ignore case. Both return new strings, so you can chain them.