padStart and trim
- Node.js course
- Beginner
- Lesson 34/116
- 5 min
Learn string formatting with .padStart and .trim.
Padding with padStart
To pad a string to a specific length you use .padStart(targetLength, padString). The string is prefixed with padString until the target length is reached. "5".padStart(3, "0") returns "005".
padStart is useful for showing codes, phone or sequence numbers at a fixed width. For example "42".padStart(6, "0") returns "000042"; this way every code in a list lines up at the same width. Its counterpart .padEnd() pads at the end.
Trimming whitespace with trim
To remove leading and trailing whitespace (space, tab, newline) from a string you use .trim(). " alex ".trim() returns "alex". Whitespace often appears around user input; trim removes it in one call.
To remove only leading whitespace use .trimStart(), only trailing use .trimEnd(). trim does not modify the original string; it returns a new one. Trimming fields like email or username makes comparisons reliable.
Practice Pad the code to 6 characters
The code variable holds "42". Declare a variable padded and assign the result of code.padStart(6, "0") to it. Then print padded with console.log. The output on a single line must be 000042.
Starter code
const code = "42";
// Declare padded with padStart and print itSample solution
const code = "42";
const padded = code.padStart(6, "0");
console.log(padded);Expected output
000042
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the padStart call
const code = "5";
const padded = code____(3, "0");
const code = "5";
const padded = code.padStart(3, "0");
Explanation: .padStart pads at the start of the string.
2 What is the result of "7".padStart(4, "0")?
"7".padStart(4, "0")- "7"
- "7000"
- "0007" Correct answer
- "0"
Explanation: padStart(4, "0") prepends three zeros; the result is "0007".
3 Match each method to its job
| Term | Meaning |
|---|---|
.padStart(n, x) |
Pads at the start |
.padEnd(n, x) |
Pads at the end |
.trim() |
Removes side whitespace |
.trimStart() |
Removes only the start |