Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.trim() — removing whitespace from both ends

trim() returns text without leading and trailing whitespace or line terminators. It leaves the original string and internal spacing unchanged and does not accept an argument specifying which characters to remove.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

text.trim()

String.prototype.trim() removes characters belonging to ECMAScript's WhiteSpace and LineTerminator sets from both ends of a string. It returns a string value without changing the original. If the entire input consists of those characters, the result is the empty string "".

Removed characters include ordinary spaces, tabs, line terminators, and the non-breaking space U+00A0. This does not mean every invisible character is removed: the zero-width space U+200B remains. Characters inside the text also remain unchanged.

Call the method as text.trim(). There is no character-selection parameter, so trim("x") does not remove the letter x. Assign the result to a variable if you need to keep it. The method is generic: String.prototype.trim.call(123) returns "123", but passing null or undefined as this causes a TypeError.

This is an ECMAScript standard-library method, not a Web API. The language specification is not a browser compatibility table; having Node.js in a project does not prove support in the target browser.

Examples

const text = "\t  Ada  Lovelace \n";
const trimmed = text.trim();
console.log(JSON.stringify(trimmed));
console.log(text === "\t  Ada  Lovelace \n");
console.log(JSON.stringify(" \t\n".trim()));

Result

"Ada  Lovelace"
true
""

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources