JavaScript String trim()

Example 1

Remove spaces with trim():

let text = "       Hello World!        ";
let result = text.trim();
Try it Yourself »

Remove spaces with replace() using a regular expression:

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

Description

The trim() method removes whitespace from both sides of a string.

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


Syntax

string.trim()

Parameters

NONE

Return Value

Type Description
A stringA string with removed whitespace from both ends.



Browser Support

trim() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all modern browsers since July 2013:

Chrome
23
IE/Edge
10
Firefox
21
Safari
6
Opera
15
Sep 2012 Sep 2012 Apr 2013 Jul 2012 Jul 2013

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.