String.prototype.trim()

trim()
Returns: string · Added in vES5 · Updated March 13, 2026 · String Methods
string trim whitespace sanitization es5

The trim() method removes whitespace characters from both ends of a string and returns a new string. This is essential for cleaning user input, sanitizing data from external sources, and preparing strings for comparison or storage.

Syntax

string.trim()

String Immutability

Strings in JavaScript are immutable — they cannot be changed after creation. Every string operation that appears to modify a string actually returns a new one. This applies to trim() as well:

const username = "  john  ";
const cleaned = username.trim();

console.log(username);  // "  john  " (unchanged)
console.log(cleaned);  // "john" (new string)

This behavior is consistent across all string methods. Always assign the returned value to a variable if you need the trimmed result.

Whitespace Characters

The trim() method removes all whitespace characters from both ends, including:

  • Regular space ( )
  • Tab (\t)
  • Newline (\n, \r\n)
  • Non-breaking space (\u00A0, often used in HTML)
  • Unicode whitespace characters from the White_Space category
// Various whitespace characters
const messy = "\t hello \u00A0\nworld\r\n   ";
console.log(messy.trim()); // "hello \u00A0\nworld"

Note that trim() only removes whitespace from the ends, not from within the string.

Use Cases

Cleaning user input

When users submit forms, whitespace often sneaks in accidentally:

function processForm(name, email) {
  const cleanName = name.trim();
  const cleanEmail = email.trim();
  
  if (!cleanName || !cleanEmail) {
    throw new Error("Name and email are required");
  }
  
  return { name: cleanName, email: cleanEmail };
}

processForm("  John Doe  ", "  john@example.com  ");
// { name: "John Doe", email: "john@example.com" }

Sanitizing data from external sources

APIs, CSV files, and databases often contain padded whitespace:

const row = "  12345 |   Product Name   |   29.99  ";
const fields = row.split("|").map(field => field.trim());

console.log(fields);
// ["12345", "Product Name", "29.99"]

Conditional logic for empty strings

Use trim() to detect truly empty input:

function isBlank(str) {
  return !str || str.trim().length === 0;
}

console.log(isBlank("   "));     // true (whitespace-only)
console.log(isBlank(""));       // true
console.log(isBlank("hello"));  // false

// Practical: validate search input
const searchTerm = "   ";
if (searchTerm.trim()) {
  // Perform search
  console.log("Searching for:", searchTerm.trim());
} else {
  console.log("Please enter a search term");
}
// "Please enter a search term"

Browser Compatibility

The trim() method is supported in all modern browsers and Node.js versions. It was introduced in ES5, making it safe to use in virtually any JavaScript environment today.

Key Behaviors

  • Returns a new string; original string is unchanged
  • Removes whitespace from both the beginning and end
  • Whitespace includes spaces, tabs, newlines, and Unicode whitespace
  • Returns an empty string if the input is only whitespace
  • Returns the original string unchanged if no whitespace exists at ends

See Also