JavaScript String trim() Method

Last Updated : 15 Jan, 2026

The trim() method is used to remove extra spaces from a string. It helps clean user input by removing unwanted whitespace.

  • Removes whitespace from both ends of the string.
  • Returns a new trimmed string.
  • The original string is not modified.

Syntax

str.trim();

Parameters

This method does not accept any parameter.

Return value

Returns a new string without any of the leading or trailing white spaces. 

Example 1: Trimming Whitespace from the End of a String.

JavaScript
// String with trailing what spaces
let s = "GeeksforGeeks     ";

// trim() method to remove while spaces
let s1 = s.trim();

console.log(s1);

Output
GeeksforGeeks

Example 2: Trimming Leading Whitespace from a String

JavaScript
// Original string with whitespace
let s = "   GeeksforGeeks";

// Trimmed string
let s1 = s.trim();

console.log(s1);

Output
GeeksforGeeks

Example 3: Trimming Whitespace from both sides of String

JavaScript
// String with whitespace
let s = "   GeeksforGeeks    ";

// Trimmed string
let s1 = s.trim();

console.log(s1);

Output
GeeksforGeeks
Comment

Explore