JavaScript String trim() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.trim() returns a new string with whitespace removed from both ends (same API as MDN String.prototype.trim()). Learn what counts as whitespace, how it differs from trimStart() / trimEnd(), cleaning form input, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

New string

03

Parameters

None

04

Removes

Both ends

05

Mutates?

No

06

Baseline

Widely available

Introduction

User input and pasted text often include accidental spaces, tabs, or newlines at the edges. trim() strips that padding from both ends so comparisons and validation stay reliable.

Middle spaces stay put — "Hello world" remains two words. For only the start or only the end, use trimStart() or trimEnd().

💡
Beginner tip

Almost always trim before comparing or storing form fields: const name = input.value.trim();

This page is part of JavaScript String Methods. Related topics include toLowerCase() and padStart().

Understanding the trim() Method

str.trim() builds a new string with leading and trailing whitespace removed. Whitespace means white space characters plus line terminators (spaces, tabs, newlines, and similar).

  • Returns a new string — the original is unchanged.
  • Takes no parameters.
  • Does not remove spaces between words.
  • Still returns a new string when there was nothing to trim.

📝 Syntax

General form of String.prototype.trim:

JavaScript
str.trim()

Parameters

None.

Return value

A new string representing str with whitespace stripped from both its beginning and end.

Exceptions

None for normal string values.

Common patterns

JavaScript
"   Hello world!   ".trim();  // "Hello world!"
"   foo  ".trim();            // "foo"
"\t\n hi \r".trim();          // "hi"
"no-spaces".trim();           // "no-spaces"
"  a  b  ".trim();            // "a  b" (middle spaces kept)

⚡ Quick Reference

GoalCode
Trim both endsstr.trim()
Trim start onlystr.trimStart()
Trim end onlystr.trimEnd()
Clean form inputinput.value.trim()
Trim + lowercasestr.trim().toLowerCase()

🔍 At a Glance

Four facts to remember about String.trim().

Returns
string

New trimmed text

Ends
both

Start and end

Middle
kept

Inner spaces stay

Mutates
no

Immutable

📋 trim() vs trimStart() vs trimEnd()

trim()trimStart()trimEnd()
Removes fromBoth endsStart onlyEnd only
Old aliastrimLeft()trimRight()
" hi ""hi""hi "" hi"
Best forForm fields / defaultsIndent-sensitive textTrailing newlines

Examples Gallery

Examples follow MDN String.trim() patterns plus everyday beginner tips. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN demos for everyday trimming.

Example 1 — Basic trim()

MDN Try it demo: spaces on both sides of a greeting.

JavaScript
const greeting = "   Hello world!   ";

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trim());
// Expected output: "Hello world!";
Try It Yourself

How It Works

Leading and trailing spaces disappear. The space between Hello and world! stays. greeting itself is unchanged.

Example 2 — Using trim()

MDN Using trim() demo with uneven padding.

JavaScript
const str = "   foo  ";
console.log(str.trim());
// 'foo'
Try It Yourself

How It Works

Three spaces on the left and two on the right are all removed in one call.

🔧 Everyday Patterns

Tabs, newlines, one-sided trim, and form cleanup.

Example 3 — Tabs and Newlines

Whitespace is more than the space bar.

JavaScript
const messy = "\t\n hi \r";

console.log(JSON.stringify(messy));
console.log(JSON.stringify(messy.trim()));
// "hi"

console.log("no-spaces".trim());
// "no-spaces"
Try It Yourself

How It Works

Tabs (\t), newlines (\n), and carriage returns (\r) at the edges are treated as whitespace and removed.

Example 4 — Both Ends vs One Side

See how trim, trimStart, and trimEnd differ.

JavaScript
const padded = "  hi  ";

console.log(JSON.stringify(padded.trim()));
// "hi"

console.log(JSON.stringify(padded.trimStart()));
// "hi  "

console.log(JSON.stringify(padded.trimEnd()));
// "  hi"
Try It Yourself

How It Works

Reach for one-sided methods when you must keep indentation or a trailing space on purpose. Default to trim() for form fields.

Example 5 — Clean Form Input

Practical pattern: trim before empty checks and case-insensitive compare.

JavaScript
function cleanUsername(raw) {
  return raw.trim().toLowerCase();
}

const typed = "  Ada  ";
const cleaned = cleanUsername(typed);

console.log(cleaned);                 // "ada"
console.log(typed.trim() === "");     // false
console.log("   ".trim() === "");     // true — empty after trim
console.log("  a  b  ".trim());       // "a  b"
Try It Yourself

How It Works

Trimming first makes " " look empty and keeps usernames consistent. Inner double spaces are not collapsed — only the edges are cleaned.

🎯 Common Use Cases

  • Form fields — names, emails, search boxes before validate/save.
  • Empty checksvalue.trim() === "" catches space-only input.
  • Normalize before compare — often chained with toLowerCase().
  • Not for mid-string spaces — use replace / regex to collapse them.
  • Not one-sided — use trimStart / trimEnd when needed.

🧠 How trim() Works

1

Scan from the start

Skip whitespace code points at the beginning.

Start
2

Scan from the end

Skip whitespace code points at the end.

End
3

Keep the middle

Copy everything between those edges unchanged.

Middle
4

Return a new string

Original string is never modified.

📝 Notes

  • Always returns a new string — assign it if you need the result.
  • Does not collapse repeated spaces inside the text.
  • Whitespace includes more than " " — tabs and line breaks count too.
  • Safe to call when there is nothing to trim.
  • Older docs may mention trimLeft / trimRight — prefer trimStart / trimEnd.

Browser & Runtime Support

String.prototype.trim() is Baseline Widely available — supported across modern browsers since July 2015 (and long before in practice).

Baseline · Widely available

String.trim()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Everyday choice for cleaning leading and trailing whitespace.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
trim() Excellent

Bottom line: Use String.trim() to remove whitespace from both ends. Use trimStart/trimEnd for one side, and replace/regex when you need to change spaces in the middle.

Conclusion

String.prototype.trim() is the simple, reliable way to clean padding from both ends of a string — especially form input. Reach for trimStart() or trimEnd() when only one side should change.

Continue with toLowerCase(), replace(), or the String methods hub.

💡 Best Practices

✅ Do

  • Trim user input before validate / store / compare
  • Use trim() === "" to catch space-only fields
  • Chain with toLowerCase() when normalizing
  • Prefer trimStart / trimEnd for one-sided needs
  • Assign the return value — original stays padded

❌ Don’t

  • Expect middle spaces to disappear
  • Forget tabs and newlines also count as whitespace
  • Mutate expectations without assignment
  • Use trim when you only need one end cleaned
  • Skip trimming before equality checks on form text

Key Takeaways

Knowledge Unlocked

Five things to remember about String.trim()

Both ends cleaned — middle kept, original unchanged.

5
Core concepts
📏 02

Removes

both ends

Role
🔢 03

Middle

spaces kept

Rule
🔍 04

Siblings

Start / End

Family
05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.trim() returns a new string with whitespace removed from both the beginning and the end. The original string is not changed.
Whitespace includes spaces, tabs, newlines, and other white space characters plus line terminators (as defined by the ECMAScript whitespace and line terminator rules).
No. Only leading and trailing whitespace are removed. Spaces between words stay. Use replace with a regex if you need to collapse inner spaces.
trim() cleans both ends. trimStart() (alias trimLeft) removes only from the start. trimEnd() (alias trimRight) removes only from the end.
No. Strings are immutable. trim() always returns a new string — even when there was nothing to remove.
Almost always when reading user input, query strings, or pasted text — trim before comparing, validating, or storing values.
Did you know?

Even when a string has no leading or trailing whitespace, trim() still returns a new string (essentially a copy). That keeps the API predictable — you never need a special “was anything trimmed?” check for correctness.

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful