String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Syntax

str.trim()

Return value

A new string representing the str stripped of whitespace from both ends.

Description

The trim() method returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself.

Polyfill

Running the following code before any other code will create trim() if it's not natively available.

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Examples

Using trim()

The following example displays the lowercase string 'foo':

var orig = '   foo  ';
console.log(orig.trim()); // 'foo'

// Another example of .trim() removing whitespace from just one side.

var orig = 'foo    ';
console.log(orig.trim()); // 'foo'

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'String.prototype.trim' in that specification.

Browser compatibility

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
trimChrome Full support 4Edge Full support 12Firefox Full support 3.5IE Full support 9Opera Full support 10.5Safari Full support 5WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11Safari iOS Full support 5Samsung Internet Android Full support 1.0nodejs Full support 0.1.100

Legend

Full support
Full support

See also