JavaScriptStringsBeginner

String.trim()

Removes whitespace from both ends of a string (returns new string).

Review the syntaxStudy the examplesOpen the coding app
string.trim()

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Removes whitespace from both ends of a string (returns new string).

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context includes all whitespace characters (space, tab, no-break space, etc.) and all line terminator characters (LF, CR, etc.). Because strings in JavaScript are immutable, this operation is non-destructive. Performance-wise, trim() is an O(N) operation where N is the length of the string, though modern engines optimize this by scanning from both ends until non-whitespace characters are found. It is an essential tool for data sanitization, especially when processing user input from form fields or parsing text files where trailing spaces might cause logic errors in comparisons or lookups.

Quick reference

Syntax

string.trim()

See it in practice

Examples

1

Basic Whitespace Removal

const greeting = '   Hello JavaScript!   ';
const cleaned = greeting.trim();
console.log(cleaned);
Output:
"Hello JavaScript!"

Removes leading and trailing space characters while preserving internal spaces.

2

Removing Tabs and Line Breaks

const multiLine = '\n\t  Content with hidden chars  \n';
console.log(multiLine.trim());
Output:
"Content with hidden chars"

The method effectively handles escape sequences like (newline) and (tab).

3

Form Input Sanitization

function validateEmail(email) {
  const sanitized = email.trim().toLowerCase();
  return sanitized.includes('@');
}

console.log(validateEmail('  User@Example.com  '));
Output:
true

Commonly used in a chain to clean and normalize user-provided data before validation.

Debug faster

Common Errors

1

TypeError

Cause: Attempting to call .trim() on null, undefined, or a non-string type like a Number.

Fix: Ensure the value is a string or use a guard clause/optional chaining.

let input = null;
// input.trim(); // Throws TypeError
let safe = (input || '').trim();
2

LogicError

Cause: Expecting trim() to modify the original string variable (mutation).

Fix: Assign the result of the trim() call to a variable, as strings are immutable.

let name = ' Sarah ';
name.trim(); 
console.log(name); // Still ' Sarah '

Runtime support

Compatibility

Node.js, BrowserAll modern browsers, IE9+ES5 (2009)

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Removes whitespace from both ends of a string (returns new string).

TypeError: Ensure the value is a string or use a guard clause/optional chaining. LogicError: Assign the result of the trim() call to a variable, as strings are immutable.