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.

To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

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'

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also