The trim()
method removes whitespace from both ends of a string and returns a new string, without modifying the original 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.).
String.prototype.trim()
Try it
Syntax
trim()
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()
.
Examples
Using trim()
The following example displays the lowercase string 'foo'
:
var orig = ' foo '; console.log(orig.trim()); // 'foo'
Specifications
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
Trim |
4
|
12
|
3.5
|
10
|
10.5
|
5
|
≤37
|
18
|
4
|
11
|
5
|
1.0
|
1.0
|
0.10.0
|
See also
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim