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 through 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 A string with spaces removed from both ends.

Browser support

trim() is an ECMAScript5 (ES5) feature.

All web browsers fully support ES5 (JavaScript 2009):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Stöd 9-11 Stöd Stöd Stöd Stöd

Relaterade sidor

JavaScript-sträng

JavaScript-strängmetoder

JavaScript-strängsökning