String.prototype.trim()

Removes whitespace and line terminators from both ends of a string.

Signature
trim()
  • Added in JavaScript ES5

Return value

stringA new string representing str stripped of whitespace from both its beginning and end. If neither end has whitespace, a new string is still returned (essentially a copy of str).

trim() strips whitespace from both ends and returns a new string. It is the first thing to call on anything a human typed.

What counts as whitespace

More than the space bar. The specification's definition covers white space characters plus line terminators: space, tab, vertical tab, form feed, no-break space (U+00A0), zero-width no-break space (U+FEFF), every Unicode space separator, and the newline characters LF, CR, U+2028 and U+2029. Text pasted from a word processor or a web page often carries a non-breaking space, and trim() removes it while a naive replace(/ /g, "") would not.

What it does not do

  • It does not touch whitespace inside the string. Collapsing runs of internal spaces needs replace(/\s+/g, " ").
  • It does not mutate. s.trim() alone is a no-op unless you assign the result — a mistake that survives review surprisingly often.
  • It does not remove arbitrary characters. There is no argument; to strip other characters use a regex.

For one end only, use trimStart() or trimEnd().

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Normalise a form field before validating or storing it
  • Clean each cell after splitting a CSV line
  • Drop a trailing newline from a line of piped input
  • Compare two labels ignoring accidental padding

Frequently asked questions

Does trim remove newlines and tabs?

Yes. trim() strips every whitespace character plus every line terminator from both ends, including tabs, newlines, carriage returns, form feeds and non-breaking spaces. It only removes them from the ends, never from the middle.

Why is my string still padded after calling trim?

Because trim() returns a new string instead of modifying the original, so the result must be assigned: s = s.trim(). If you did assign it, the remaining characters are probably not whitespace — a zero-width space (U+200B), for example, is not trimmed.

How do I remove all spaces from a string, not just the ends?

Use replace with a global regex: str.replace(/\s+/g, "") deletes every whitespace run, and str.trim().replace(/\s+/g, " ") collapses internal runs to a single space. trim() only ever touches the two ends.

More examples

Cleaning a split CSV row

The raw split keeps every stray space, so " name " would never equal "name". Mapping trim over the parts gives ["name","age","city"], and the final count of 1 shows how trimming turns a whitespace-only field into a detectable empty string.

Example · javascript
const row = " name , age ,  city ";

console.log(row.split(","));
console.log(row.split(",").map((s) => s.trim()));

// Blank-field detection after trimming
const fields = " a , ,c ".split(",").map((s) => s.trim());
console.log(fields);
console.log(fields.filter((f) => f === "").length);

Trim does not collapse internal spaces

trim() alone leaves "too many spaces" with its internal runs intact. Adding a /\s+/g replace normalises them to single spaces; the last two lines produce the same result, so the order does not matter as long as both steps happen.

Example · javascript
const messy = "   too    many   spaces   ";

console.log(JSON.stringify(messy.trim()));
console.log(JSON.stringify(messy.trim().replace(/\s+/g, " ")));
console.log(JSON.stringify(messy.replace(/\s+/g, " ").trim()));

Validating required input

The first call returns "Ada" with the padding gone; the other three return null. Coercing with String(value ?? "") before trimming means undefined and null do not throw, which is the usual shape of a form-field guard.

Example · javascript
function required(value) {
  const v = String(value ?? "").trim();
  return v === "" ? null : v;
}

console.log(required("  Ada "));
console.log(required("   "));
console.log(required("\n\t"));
console.log(required(undefined));

Discussion

  • Be the first to comment on this lesson.