0
0
JavascriptHow-ToBeginner · 3 min read

How to Trim Whitespace from String in JavaScript

Use the trim() method on a string to remove whitespace from both the start and end. For example, str.trim() returns a new string without leading or trailing spaces.
📐

Syntax

The trim() method is called on a string and returns a new string with whitespace removed from both ends.

  • str: The original string.
  • str.trim(): Returns a new string without spaces at the start or end.
javascript
const str = "  hello world  ";
const trimmed = str.trim();
💻

Example

This example shows how trim() removes spaces from the start and end of a string but leaves spaces inside the string intact.

javascript
const original = "   Hello, JavaScript!   ";
const trimmed = original.trim();
console.log("Original: '" + original + "'");
console.log("Trimmed: '" + trimmed + "'");
Output
Original: ' Hello, JavaScript! ' Trimmed: 'Hello, JavaScript!'
⚠️

Common Pitfalls

Some common mistakes include:

  • Expecting trim() to remove spaces inside the string (it only removes from start and end).
  • Trying to modify the original string (strings are immutable; trim() returns a new string).
  • Using trim() on non-string values without converting them first.
javascript
const str = "  hello world  ";
// Wrong: expecting original string to change
str.trim();
console.log(str); // Still has spaces

// Right: assign the trimmed string
const trimmed = str.trim();
console.log(trimmed); // Spaces removed
Output
hello world hello world
📊

Quick Reference

Summary of trimming methods:

MethodDescription
trim()Removes whitespace from both start and end of a string.
trimStart() / trimLeft()Removes whitespace from the start of a string.
trimEnd() / trimRight()Removes whitespace from the end of a string.

Key Takeaways

Use trim() to remove spaces from the start and end of a string.
trim() does not remove spaces inside the string.
Strings are immutable; always use the returned trimmed string.
Use trimStart() or trimEnd() to remove spaces only from one side.