jQuery trim() Method

Beginner
6 min read
Updated: Oct 2026
4 examples
Live preview

What Is trim()?

jQuery.trim(str) (alias $.trim) removes whitespace from the start and end of a string (added in jQuery 1.0). Spaces, tabs, newlines, and non-breaking spaces in the middle are kept.

Remember
$.trim(str)  → trimmed string (new string)

$.trim(" hello, how are you? ")  → "hello, how are you?"

// Modern equivalent:
" hello, how are you? ".trim()
NeedUse
Trim both ends (legacy)$.trim(str)
Trim both ends (new code)str.trim()
Trim start onlystr.trimStart()
Trim end onlystr.trimEnd()

How to Use trim()

Pass a string, get a cleaned copy back, then validate or save it.

  1. Start with a string that may have edge spaces (form value, paste, API text).
  2. Call $.trim(str) — or str.trim() in new code.
  3. Use the returned string (the original is unchanged).
  4. Optionally check for blank input with trimmed === "".
PieceRequired?Role
strYesString to trim
Return—New string without leading/trailing whitespace
Middle spaces—Preserved

Pseudocode

Pseudocode
function trim(str):
    remove whitespace from start of str
    remove whitespace from end of str
    return new string   // middle unchanged

// Typical flow:
raw = $("#name").val()
name = $.trim(raw)          // or raw.trim()
if name === "":
    show "required"
else:
    save name

Cheat Sheet

Keep these facts handy while cleaning strings with jQuery.

TopicDetail
SyntaxjQuery.trim(str) / $.trim(str)
SincejQuery 1.0
StatusDeprecated 3.5 · removed 4.0
RemovesLeading/trailing spaces, tabs, newlines, NBSP
KeepsWhitespace in the middle of the string
Modern replacementString.prototype.trim()
HTML helper useTrim before $.parseHTML()

Live Preview

Pick a sample string, run $.trim, and compare before/after.

Browser demo of $.trim() — same ideas as the examples below.

Result
sample = Official greeting
before → " hello, how are you? "
after  → "hello, how are you?"

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Official Demo

Official jQuery API pattern in one line.

jQuery
var result = $.trim(" hello, how are you? ");

console.log(result);  // "hello, how are you?"
Try It Yourself

How It Works

  1. Input. The string has one space at each end.
  2. Trim. $.trim removes those edge characters.
  3. Middle. The space after the comma stays — only edges change.
  4. Return. You get a new string; the original argument is not mutated.

Example 2 — Middle Spaces Are Kept

Extra spaces between words are not collapsed.

jQuery
var text = "  hello   world  ";
var cleaned = $.trim(text);

console.log(JSON.stringify(cleaned));  // "hello   world"
Try It Yourself

How It Works

  1. Edges. Leading and trailing double spaces are removed.
  2. Middle. The three spaces between hello and world remain.
  3. JSON.stringify. Quotes make the remaining spaces easy to see in output.
  4. Tip. To collapse all runs of spaces, use a regex replace — not trim.

Example 3 — Newlines and Tabs

Pasted text often includes line breaks and tabs at the edges.

jQuery
var pasted = "\n\t  Save draft  \r\n";
var cleaned = $.trim(pasted);

console.log(JSON.stringify(cleaned));  // "Save draft"
Try It Yourself

How It Works

  1. Whitespace kinds. \n, \t, \r, and spaces all count at the edges.
  2. Trim. Every leading/trailing whitespace character is stripped.
  3. Result. Only the visible words remain: Save draft.
  4. Forms. Useful after reading a textarea value before saving.

Example 4 — Migrate to String.prototype.trim()

Same result with the native API preferred since jQuery 3.5.

jQuery
var raw = "   codetofun   ";

var withJquery = $.trim(raw);
var withNative = raw.trim();

console.log(withJquery === withNative);  // true
console.log(withNative.length);          // 9
Try It Yourself

How It Works

  1. Same input. One padded string is trimmed two ways.
  2. Legacy. $.trim still works on jQuery 3.x.
  3. Native. raw.trim() is the supported replacement.
  4. Migrate. Replace $.trim(str) with String(str).trim() when the value might not be a string.

Edge Cases & Pitfalls

Check these before cleaning real form or API text.

deprecated

Removed in jQuery 4.0

Do not start new features on $.trim. Use str.trim() so upgrades stay smooth.

types

Native trim is strings-only

String.prototype.trim does not accept null, undefined, or numbers. Migrate with String(value).trim() when input type varies.

middle

Does not collapse inner spaces

trim never squeezes "a   b" into "a b". Use a replace if you need that.

blank

Whitespace-only becomes ""

After trim, " " and "\n\t" are empty strings — handy for required-field checks.

Browser Support

jQuery.trim() existed in jQuery 1.0–3.x, was deprecated in 3.5, and removed in 4.0. Prefer native String.prototype.trim() in all modern browsers. This page focuses on browser use with jQuery loaded.

✓ Deprecated · jQuery 3.5

jQuery.trim()

Available with jQuery 1.0–3.x in Chrome, Firefox, Safari, and Edge. Prefer String.prototype.trim() for new code. Not present in jQuery 4.0.

Legacy Prefer .trim()
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
$.trim() Legacy

Bottom line: Learn $.trim() for legacy jQuery code. Write str.trim() (or String(value).trim()) in new projects.

Performance Notes

ApproachCostBest for
str.trim()O(n) in string lengthAll new code
$.trim(str)O(n)Legacy jQuery 1.x–3.x only
Trim once per fieldCheapest habitForm submit / blur handlers

Trimming is cheap for normal form strings. Prefer one trim when you read the value, then reuse that cleaned string for validation and save.

Key Takeaways

  • Role: $.trim(str) removes edge whitespace only.
  • Modern: use str.trim() instead.
  • Middle: inner spaces stay; trim does not collapse them.
  • Status: deprecated in 3.5, removed in 4.0.

One line: know $.trim for legacy jQuery, but clean strings with str.trim() (and String(value).trim() when needed) in every new project.

Frequently Asked Questions

jQuery.trim(str) removes whitespace — spaces, tabs, newlines, and non-breaking spaces — from the beginning and end of a string. Whitespace in the middle stays unchanged. It returns a new string and does not modify the original.
The jQuery API demo is $.trim(" hello, how are you? "), which returns "hello, how are you?" — outer spaces gone, inner spacing preserved.
Both strip leading and trailing whitespace. Native String.prototype.trim() is the modern standard. $.trim was deprecated in jQuery 3.5 and removed in 4.0. Native trim only works on strings — convert with String(value).trim() when migrating non-string input.
No. Only leading and trailing whitespace is removed. $.trim(" hello world ") returns "hello world".
Not for new code. Prefer " text ".trim() or String(value).trim(). Keep $.trim only while maintaining jQuery 1.x–3.x legacy code.
Common uses included cleaning form values before validation, normalizing pasted textarea text, and preparing strings for comparison in older jQuery plugins.

Next: now()

Learn how jQuery returns the current timestamp in milliseconds.

now() tutorial →

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.

9 people found this page helpful