JavaScript String trim()

Definition and usage

trim() The method removes spaces from both sides of the string.

trim() The method does not change the original string.

Instance

Example 1

Using trim() Remove spaces:

let text = "       Hello World!        ";
let result = text.trim();

Try it yourself

Example 2

Using regular expressions by replace() Remove spaces:

let text = "       Hello World!        ";
let result = text.replace(/^\s+|\s+$/gm,'');

Try it yourself

Syntax

string.trim()

Parameter

No parameters.

Return value

Type Description
String The string with spaces removed from both ends.

Browser support

trim() is an ECMAScript5 (ES5) feature.

All browsers fully support ES5 (JavaScript 2009):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support

Related Pages

JavaScript String

JavaScript String Methods

JavaScript String Search