String

String.prototype.trim

Removes whitespace from both ends of a string and returns a new string, without modifying the original

Syntax

JavaScript
string.trim()

Return Value

A new string with whitespace removed from both ends

Examples

Basic Usage
const str = '   Hello World   ';
console.log(str.trim()); // 'Hello World'
Practical Example
const input = '  [email protected]  \n';
const cleaned = input.trim();
console.log(cleaned); // '[email protected]'
Advanced Usage
const lines = '  foo  \n  bar  \n  baz  '.split('\n');
const trimmed = lines.map(l => l.trim());
console.log(trimmed); // ['foo', 'bar', 'baz']

Understanding String.prototype.trim

The String.prototype.trim method in JavaScript removes whitespace from both ends of a string and returns a new string, without modifying the original. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.

The method signature is string.trim(). When called, it returns a new string with whitespace removed from both ends. Understanding when and how to use trim() helps you write more expressive, readable code.

Common use cases for String.prototype.trim include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-trimstart, string-trimend, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for String.prototype.trim is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More String Methods

Other methods in the String object

Related Tools

More String Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.