Strings: Trimming and Padding

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


JavaScript provides methods to add or remove whitespace from strings.

trim()

Removes whitespace from both ends of a string:

'Testing'.trim() //'Testing'
' Testing'.trim() //'Testing'
' Testing '.trim() //'Testing'
'Testing '.trim() //'Testing'

trimStart()

Removes whitespace from the beginning of a string:

'Testing'.trimStart() //'Testing'
' Testing'.trimStart() //'Testing'
' Testing '.trimStart() //'Testing '
'Testing '.trimStart() //'Testing '

trimEnd()

Removes whitespace from the end of a string:

'Testing'.trimEnd() //'Testing'
' Testing'.trimEnd() //' Testing'
' Testing '.trimEnd() //' Testing'
'Testing '.trimEnd() //'Testing'

padStart()

Pads the beginning of a string to reach a specific length:

'test'.padStart(4)          //'test'
'test'.padStart(5)          //' test'
'test'.padStart(8)          //'    test'
'test'.padStart(8, 'abcd')  //'abcdtest'

The second parameter specifies the padding string (default is space).

Common use case—padding numbers:

'1'.padStart(2, '0')  //'01'
'12'.padStart(2, '0') //'12'

padEnd()

Pads the end of a string to reach a specific length:

'test'.padEnd(4)          //'test'
'test'.padEnd(5)          //'test '
'test'.padEnd(8)          //'test    '
'test'.padEnd(8, 'abcd')  //'testabcd'

Introduced in ES2017.

Lessons in this unit:

0: Introduction
1: String Basics
2: Accessing Characters
3: Searching Strings
4: Extracting Substrings
5: Transforming Strings
6: Modifying Strings
7: ▶︎ Trimming and Padding
8: String Recipes
9: Unicode and UTF-8
10: Printable ASCII characters list
11: Non-printable ASCII characters list