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.
Syntax
Start with these common calls. Keep them short and readable.
jQuery
$.trim(str) → trimmed string (new string)
$.trim(" hello, how are you? ") → "hello, how are you?"
// Modern equivalent:
" hello, how are you? ".trim()
Call
What it does
trim()
Learn jQuery.trim(): remove leading and trailing whitespace, keep middle spaces, official demo, migrate to String.prototype.trim, examples, pitfalls, and FAQs.
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Start with a string that may have edge spaces (form value, paste, API text).
Step 2
Call $.trim(str) — or str.trim() in new code.
Step 3
Use the returned string (the original is unchanged).
Return Value
Return Value
Description
Value / undefined
Getters usually return a value from the first matched element, or undefined when nothing applies.
jQuery Examples
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?"
Whitespace kinds.\n, \t, \r, and spaces all count at the edges.
Trim. Every leading/trailing whitespace character is stripped.
Result. Only the visible words remain: Save draft.
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.