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



Return value

A new string representing str stripped of whitespace from both its beginning and end.

If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str), with no exception being thrown.

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


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, '');


Using trim()

The following example displays the lowercase string 'foo':

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


ECMAScript Language Specification (ECMAScript)
# sec-string.prototype.trim

Browser compatibility

BCD tables only load in the browser

See also