Favorites

JavaScript String.prototype.trim() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
String.prototype.trim()
JavaScript String Instance methodThis method is supported by all modern browsers.
Updated 28th November 2026

The trim() method removes white space, including spaces, tabs and line breaks, from both ends of a string.

Description

The trim() method returns a new string with white space removed from both ends. White space includes spaces, tabs, non-breaking spaces and line terminators. It's commonly used to clean up form input before checking or saving it. Use trimStart() or trimEnd() to trim only one side.

It doesn't remove white space from the middle of a string; to collapse runs of spaces into one, use str.replace(/\s+/g, ' '). It also leaves zero-width characters alone, because they don't count as white space.

Trimming is worth doing before checking whether a required field is empty, since a value of only spaces would otherwise pass, and before comparing or storing values typed by users. Native form validation doesn't trim values for you.

Syntax

string.trim()

Return Value

A new string with white space removed from both ends.

Example

const input = '   sam@example.com \n';
console.log('[' + input.trim() + ']');
console.log('   '.trim() === '');

Browser Support

The following information will show you the current browser support for the String.prototype.trim() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee