Sub topic 7
Changing Case, Trimming, and Padding
This chapter covers the methods that reshape a string without searching inside it: toUpperCase, toLowerCase and their locale-aware versions, the three trim methods, padStart and padEnd, and repeat. It assumes you can run JavaScript in Node.js or a browser console, know basic array methods such as map, and have read the earlier chapters on immutability and indexing. Each method here returns a new string and leaves the original unchanged, as described in the immutability chapter.
The everyday uses are simple. Most of the detail in this chapter is about where they stop being simple: characters whose case mapping changes the string's length, whitespace that trim does or does not remove, and padding that counts UTF-16 code units instead of visible characters.
Case Conversion
toUpperCase and toLowerCase
Both methods map every character to its uppercase or lowercase form using the Unicode default case mappings, which do not depend on any language setting.
const title = "Hello, World";
console.log(title.toUpperCase()); // HELLO, WORLD
console.log(title.toLowerCase()); // hello, world
console.log(title); // Hello, World (unchanged)
console.log("123 !?".toUpperCase()); // 123 !? (characters with no case pass through)Case mapping can change length
Most developers expect case conversion to keep the length the same. Unicode does not guarantee that. Some characters map to more than one character, and some lowercase mappings add a combining mark.
const sharp = "straße";
console.log(sharp.toUpperCase()); // STRASSE
console.log(sharp.length, sharp.toUpperCase().length); // 6 7
const ligature = "\uFB01"; // "fi" ligature, one character
console.log(ligature.toUpperCase()); // FI
console.log(ligature.toUpperCase().length); // 2
const dottedI = "\u0130"; // "İ", capital I with dot above
console.log(dottedI.toLowerCase().length); // 2 ("i" + combining dot U+0307)This matters if you compute positions in one version of a string and then use them on the case-converted version. An index found in s.toUpperCase() can point to the wrong place in s. Search a lowercased copy and then slice the lowercased copy too, or avoid mixing the two.
Locale-sensitive versions
toLocaleUpperCase and toLocaleLowerCase take an optional locale tag. For most languages the result matches the default methods. Turkish and Azerbaijani are the well-known exceptions: they have a dotted and a dotless i, so the case pairs differ from English.
console.log("i".toUpperCase()); // I
console.log("i".toLocaleUpperCase("tr")); // İ (U+0130)
console.log("I".toLowerCase()); // i
console.log("I".toLocaleLowerCase("tr")); // ı (U+0131, dotless)Choose the version based on who reads the result:
| Purpose | Method | Reason |
|---|---|---|
| Display text to a user in their language | `toLocaleUpperCase(userLocale)` | Matches the reader's rules for their language |
| Normalize identifiers, keys, protocol tokens | `toUpperCase` / `toLowerCase` | Same result on every machine and in every locale |
| Case-insensitive comparison for users | `localeCompare` or `Intl.Collator` | Handles cases that simple case folding misses |
Case-insensitive comparison pitfalls
The usual approach, a.toLowerCase() === b.toLowerCase(), works for plain ASCII. It fails for ß, because lowercasing "STRASSE" gives "strasse", and that does not equal "straße". Uppercasing both sides happens to fix this pair, but no single direction covers every script. For user-facing comparisons, use localeCompare with sensitivity: "base", which the locale comparison chapter covers.
const a = "straße";
const b = "STRASSE";
console.log(a.toLowerCase() === b.toLowerCase()); // false
console.log(a.toUpperCase() === b.toUpperCase()); // trueTrimming Whitespace
trim, trimStart, trimEnd
trim removes whitespace from both ends of a string. trimStart and trimEnd remove it from one end. The older names trimLeft and trimRight still exist as aliases. Prefer the newer names, because "start" and "end" stay correct for right-to-left text.
const raw = " \t [email protected] \n";
console.log(JSON.stringify(raw.trim())); // "[email protected]"
console.log(JSON.stringify(raw.trimStart())); // "[email protected] \n"
console.log(JSON.stringify(raw.trimEnd())); // " \t [email protected]"
console.log("a b".trim()); // a b (interior spaces are kept)Trimming never touches the middle of the string. To collapse internal runs of spaces, use replace(/\s+/g, " "), covered in the replacing chapter.
What counts as whitespace
The trim methods remove the characters the language specification defines as whitespace and line terminators. That set is larger than space, tab, and newline:
| Character | Code point | Trimmed? |
|---|---|---|
| Space, tab, vertical tab, form feed | U+0020, U+0009, U+000B, U+000C | Yes |
| Line feed, carriage return | U+000A, U+000D | Yes |
| Non-breaking space | U+00A0 | Yes |
| Byte order mark | U+FEFF | Yes |
| Line and paragraph separators | U+2028, U+2029 | Yes |
| Other Unicode space separators (e.g. em space, ideographic space) | U+2003, U+3000 | Yes |
| Zero-width space | U+200B | No |
| Zero-width joiner | U+200D | No |
The zero-width space is the one that causes bugs. It often arrives in text pasted from web pages or chat apps. trim leaves it in place, so a value that looks empty fails an emptiness check.
const pasted = "\u200Bhello\u00A0";
console.log(pasted.trim().length); // 6 (NBSP removed, zero-width space kept)
const cleaned = pasted.replace(/^[\s\u200B]+|[\s\u200B]+$/g, "");
console.log(cleaned.length); // 5Trimming form input
A common pattern is to trim and lowercase input before you store or compare it. Do the trimming before any validation, so that " " counts as empty.
function normalizeEmail(input) {
const value = String(input ?? "").trim().toLowerCase();
if (value === "") {
throw new Error("Email is required");
}
return value;
}
console.log(normalizeEmail(" [email protected] ")); // [email protected]Padding
padStart and padEnd
padStart(targetLength, padString) adds characters to the front until the string reaches targetLength. padEnd adds them to the back. The default padString is a single space.
console.log("7".padStart(3, "0")); // 007
console.log("7".padEnd(3, ".")); // 7..
console.log("abc".padStart(6)); // " abc"
console.log("abc".padStart(10, "123")); // 1231231abc (pad repeated, then cut)
console.log("abcdef".padStart(3, "0")); // abcdef (already long enough)
console.log("abc".padStart(6, "")); // abc (empty pad string adds nothing)Three rules explain every result:
- If
targetLengthis less than or equal to the current length, the original string comes back unchanged. Padding never truncates. - The pad string is repeated as many times as needed, and the last copy is cut off to fit exactly.
- An empty pad string means nothing gets added.
Numbers have no padStart method, so convert them to strings first:
function formatTime(totalSeconds) {
const m = Math.floor(totalSeconds / 60);
const s = totalSeconds % 60;
return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}
console.log(formatTime(65)); // 01:05
console.log(formatTime(600)); // 10:00Padding negative numbers with zeros puts the zeros before the minus sign: String(-5).padStart(3, "0") gives "0-5". Pad the absolute value and add the sign back yourself.
Aligning columns
padEnd for text and padStart for numbers produce aligned plain-text output in logs and CLI tools:
const rows = [
["apples", 3],
["kiwis", 120],
["pears", 45],
];
for (const [name, qty] of rows) {
console.log(name.padEnd(8, ".") + String(qty).padStart(5));
}
// apples...... 3
// kiwis....... 120
// pears....... 45Padding counts code units
The target length is measured in UTF-16 code units, the same unit as length. Emoji and other characters outside the Basic Multilingual Plane take two units. A multi-unit pad string can then be cut in the middle and leave half of a surrogate pair:
const padded = "x".padStart(4, "\u{1F600}");
console.log(padded.length); // 4
console.log([...padded].length); // 3: emoji, lone high surrogate, "x"
console.log(padded.codePointAt(2)); // 55357 (a broken half character)Column alignment also breaks for wide characters such as CJK ideographs and emoji, which take up two columns in most terminals. If you need to align text like that, measure display width with a library built for it.
Repeating Strings
repeat(count) returns the string concatenated count times.
console.log("ab".repeat(3)); // ababab
console.log("-".repeat(20)); // --------------------
console.log("x".repeat(0)); // "" (empty string)
console.log("ab".repeat(2.9)); // abab (fraction truncated)
try {
"a".repeat(-1);
} catch (e) {
console.log(e.name); // RangeError
}A negative count or Infinity throws a RangeError. A count that would push the result past the engine's maximum string length also throws a RangeError. If the count comes from user input or arithmetic, clamp it with Math.max(0, n) first.
Choosing a Method
Exercises
Exercise
What do "straße".toUpperCase().length and "abc".padStart(2, "*") return, and why?
Show answer
The first returns 7, because "ß" uppercases to the two letters "SS", which makes the string one character longer. The second returns "abc", because the target length 2 is shorter than the string's current length, and padStart never truncates.
Exercise
A form field rejects " " as empty after trimming, but a value pasted from a web page that looks blank passes the check. What is the likely cause, and how do you fix it?
Show answer
The pasted value probably contains a zero-width space (U+200B). It is not in the whitespace set that trim removes. Strip it explicitly, for example value.replace(/^[\s\u200B]+|[\s\u200B]+$/g, ""), before you check whether the value is empty.
Exercise
Write a function formatId(n) that returns a non-negative integer as a 6-digit string padded with zeros (formatId(42) gives "000042") and throws a RangeError for negative input.
Show answer
function formatId(n) { if (n < 0) throw new RangeError("negative id"); return String(n).padStart(6, "0"); } Numbers have no padStart method, so String(n) converts the number first. Checking for negatives avoids output like "0000-5".
Exercise
Why might code that calls header.toLocaleLowerCase() to match "TITLE" against "title" fail on some servers?
Show answer
With no argument, toLocaleLowerCase uses the runtime's default locale. In a Turkish locale, "I" lowercases to the dotless "ı", so "TITLE" becomes "tıtle" and no longer equals "title". Use toLowerCase() for machine-readable text.