Codectionary / Developer documentation / JavaScript

trim(), trimStart(), trimEnd()

trim() removes whitespace from both ends of a string, commonly used to clean up user input before validation or storage. trimStart() and trimEnd() (aliases: trimLeft/trimRight) remove whitespace from only the beginning or end respectively.

Syntax

str.trim()
str.trimStart()
str.trimEnd()

Examples

Basic Trimming

Cleaning whitespace from user input.

const input = "   hello world   ";

console.log(trim = input.trim());       // "hello world"
console.log(input.trimStart());          // "hello world   " - only leading removed
console.log(input.trimEnd());            // "   hello world" - only trailing removed

Validating Trimmed Input

A common real-world pattern for form validation.

function validateUsername(input) {
  const trimmed = input.trim();
  if (trimmed.length === 0) {
    return "Username cannot be empty or just whitespace";
  }
  return `Valid username: ${trimmed}`;
}

console.log(validateUsername("   ")); // "Username cannot be empty or just whitespace"
console.log(validateUsername("  alice  ")); // "Valid username: alice"

Best practices

  • Always trim() user input before validation checks (like checking for empty strings) to catch whitespace-only submissions
  • Trim input before storing it, to avoid inconsistent data caused by accidental leading/trailing spaces
  • Use trimStart()/trimEnd() specifically when only one side needs cleaning, such as preserving intentional trailing formatting
  • Remember trim() only removes whitespace characters (spaces, tabs, newlines), not other characters like punctuation

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation