Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JavaScript · Function

trim

trim() returns a new string with whitespace and line terminators removed from both ends of the string. It leaves the original string unchanged.

How it works

Call trim() on a string to create a new string with whitespace and line terminators removed from its beginning and end. The method does not mutate the original string; if no trimming is needed, it still returns a new string.

Syntax

trim()

Returns

A new string representing the input string with whitespace removed from its beginning and end.

Key points

  • trim() removes surrounding whitespace at both ends and produces a new string.
  • Calling trim() does not change the string value on which it was called.
  • Use trimStart() for the beginning only or trimEnd() for the end only.
  • Its trimming set includes whitespace characters and line terminators.
  • Even an already-trimmed string results in a separate returned string value.

Common mistakes

  • The original string is not returned directly, even when it contains no surrounding whitespace.
  • The method removes both whitespace characters and line terminators, not merely ordinary spaces.

Example: Trim both ends of a string

const raw = "  hello, JavaScript!\n";
const clean = raw.trim();

console.log(clean); // "hello, JavaScript!"
console.log(raw);   // "  hello, JavaScript!\n"

This removes whitespace at both ends while leaving the original string unchanged.

When to use it

Normalize input

Clean user-entered text before validation or storage.

Clean configuration values

Remove accidental surrounding whitespace from configuration or environment values.

Standardize text

Prepare text for reliable comparisons or display.

  • String.prototype.trimStart()
  • String.prototype.trimEnd()

Source: String.prototype.trim () - JavaScript | MDN. Checked 2026-10-15.