Trimming and Padding Strings
Trimming and padding are opposites. The trim methods remove whitespace from the ends of a string, which is the usual first step with text typed by a user. The padding methods add characters to the ends until a string reaches a given length, which lines up columns and gives numbers a fixed width. All of them return a new string.
Trimming
Section titled “Trimming”trim() removes whitespace from both ends, trimStart() from the start only and trimEnd() from the end only. Whitespace includes spaces, tabs and line breaks. JSON.stringify() is used here to make the remaining whitespace visible.
const input = ' alice@example.com \n';
console.log(JSON.stringify(input.trim()));console.log(JSON.stringify(input.trimStart()));console.log(JSON.stringify(input.trimEnd()));This prints:
"alice@example.com""alice@example.com \n"" alice@example.com"trimLeft() and trimRight(), which appear in older code, are other names for trimStart() and trimEnd(), kept so that old pages still work. Trim methods has more detail, including which characters count as whitespace.
Padding
Section titled “Padding”padStart(length, filler) adds the filler to the start until the string is length characters long, and padEnd() adds it to the end. The filler defaults to a space. A receipt is a good use, because the names line up on the left and the prices on the right.
const items = [['Tea', 2.5], ['Scone', 3], ['Jam', 1.25]];
for (const [name, price] of items) { console.log(name.padEnd(10, '.') + price.toFixed(2).padStart(6));}This prints:
Tea....... 2.50Scone..... 3.00Jam....... 1.25Padding methods covers numbers, hex colours and the edge cases.
Using them together
Section titled “Using them together”Trim first, so that stray whitespace in the input does not upset the padding.
const raw = [' apples ', 'pears', '\tplums\n'];const cleaned = raw.map((fruit) => fruit.trim());
console.log(cleaned);console.log(cleaned.map((fruit) => fruit.padStart(8)).join('|'));This prints:
[ 'apples', 'pears', 'plums' ] apples| pears| plumsSteve Griffith covers this topic in his video Trimming and Padding Strings.