trim, padStart, padEnd
Learn to trim whitespace and pad a string to a length with padStart/padEnd.
Trimming whitespace
The trim method removes spaces, tabs and newlines from the start and end of a string. It leaves spaces in the middle untouched. It returns the cleaned string as a new value.
This is essential for user input: " alex ".trim() returns "alex". Leftover spaces break matching and searching, and trim prevents that.
padStart and padEnd
The padStart(targetLength, padString) method pads a string from the left, and padEnd from the right, up to a target length. The pad string fills the missing space.
For example "7".padStart(4, "0") returns "0007". It is perfect for invoice numbers, hours and fixed-width codes. If the string already meets or exceeds the target, nothing is added.
Exercise Clean the email input
Use trim to remove leading and trailing spaces from email and store it in clean. Print the result.
Show example solution
const email = " alex@x.com ";
// trim the whitespace
const clean = email.trim();
console.log(clean);
Exercise Pad the invoice number to 5 digits
Pad invoiceNo on the left to 5 digits, filling missing places with "0". Store the result in formatted and print it.
Show example solution
const invoiceNo = "84";
// pad on the left to 5 digits with 0
const formatted = invoiceNo.padStart(5, "0");
console.log(formatted);
Test yourself
-
What does " hi ".trim() return?
" hi ".trim()- ' hi'
- 'hi '
- ' hi '
- 'hi'
Show answer
'hi' — Correct. trim removes both leading and trailing spaces and leaves the middle alone.
-
Pad the number to 4 digits
const n = "7"; const code = n.____; console.log(code);Show answer
const n = "7"; const code = n.padStart(4, "0"); console.log(code); -
Match call to result
- " alex ".trim()
- "alex"
- "7".padStart(3, "0")
- "007"
- "5".padEnd(3, "-")
- "5--"
- "12".padStart(3, "0")
- "012"