SyntaxStudy
Sign Up
JavaScript Padding, Trimming, and Formatting Strings
JavaScript Beginner 6 min read

Padding, Trimming, and Formatting Strings

Padding, Trimming, and Formatting Strings

Presenting data to users often requires normalising whitespace or aligning values into columns. JavaScript provides a small but complete set of string methods for these tasks, available on all modern browsers and Node.js.

Trimming Whitespace

trim() removes leading and trailing whitespace (spaces, tabs, newlines). trimStart() and trimEnd() remove whitespace from only one side, which is useful when you want to preserve intentional indentation on one end.

Padding

padStart(targetLength, padString) prepends the pad string until the string reaches targetLength. padEnd appends instead. Both methods are commonly used to zero-pad numbers or align tabular output. If the pad string is longer than one character, it is repeated and then truncated to fit.

Repeat

repeat(count) returns a new string containing the original repeated count times. It is handy for generating separators, test data, or visual indentation.

Case Conversion

toUpperCase() and toLowerCase() convert all alphabetic characters. toLocaleUpperCase() and toLocaleLowerCase() respect locale-specific rules, important for languages like Turkish where case rules differ from ASCII.

Example
console.log('  hello  '.trim());       // 'hello'
console.log('  hello  '.trimStart()); // 'hello  '
console.log('  hello  '.trimEnd());   // '  hello'
console.log('5'.padStart(3, '0'));    // '005'
console.log('hi'.padEnd(6, '.'));     // 'hi....'
const hours = String(9).padStart(2, '0');
const mins  = String(5).padStart(2, '0');
console.log(hours + ':' + mins);      // 09:05
console.log('ha'.repeat(3));          // hahaha
console.log('Hello World'.toLowerCase()); // hello world
console.log('hello world'.toUpperCase()); // HELLO WORLD
Pro Tip

Always trim() user input before validation or storage — accidental leading/trailing spaces are among the most common causes of failed string comparisons.