JavaScript String Whitespace, Padding and Repetition
Quick answer
Trimming removes specified leading or trailing whitespace; padding grows a string to a target code-unit length; repeat concatenates copies.
How it works
trim, trimStart and trimEnd remove ECMAScript whitespace and line terminators at their respective edges, not inside. padStart(targetLength, padString) and padEnd repeat and truncate filler to reach the target; they do not shorten existing text. repeat(count) truncates a finite fractional count toward zero and rejects negative or infinite counts after conversion.
const label = " A B ";console.log(JSON.stringify(label.trim()));Expected output in Node.js:
"A B"Only the two outer edges are trimmed.
console.log("42".padStart(5, "0"), "ha".repeat(2));Expected output in Node.js:
00042 hahaPadding targets five units; repeat makes two copies.
Common mistakes
Padding to a string length is not visual alignment for variable-width fonts or grapheme clusters.
Practice
Clean an input identifier and pad a short numeric label to a fixed unit length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript String Whitespace, Padding and Repetition — Knowledge Check
Apply the taught concept and predict the output.
What does padEnd return when the target is shorter than the string?
Which method removes only trailing whitespace?
What does repeat(0) return for a nonempty string?
What is the exact console output in JavaScript String Whitespace, Padding and Repetition example 1?
const label = " A B ";console.log(JSON.stringify(label.trim()));What is the exact console output in JavaScript String Whitespace, Padding and Repetition example 2?
console.log("42".padStart(5, "0"), "ha".repeat(2));