Web/JavaScript/Reference/Global objects/String/trim

From Get docs


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.).


The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

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

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
trim Chrome

Full support 4

Edge

Full support 12

Firefox

Full support 3.5

IE

Full support 9

Opera

Full support 10.5

Safari

Full support 5

WebView Android

Full support ≤37

Chrome Android

Full support 18

Firefox Android

Full support 4

Opera Android

Full support 11

Safari iOS

Full support 5

Samsung Internet Android

Full support 1.0

nodejs

Full support 0.1.100

Legend

Full support  
Full support


See also