JavaScript trim()Method
Examples
Remove whitespace from both ends of a string:
var str = " Example ";
alert(str.trim());
Output:
Example
Try it yourself »
Definition and Usage
The trim() method is used to remove whitespace from both ends of a string. Whitespace includes spaces, tabs, newlines, and other whitespace characters.
The trim() method does not change the original string.
The trim() method does not apply to null, undefined, or Number types.
Browser Support
The numbers in the table indicate the first browser version that supports this property.
| Method | |||||
|---|---|---|---|---|---|
| trim() | 10.0 | 9.0 | 3.5 | 5.0 | 10.5 |
Syntax
string.trim()
Parameter Values
None.Return Value
| Type | Description |
|---|---|
| String | Returns a string with whitespace removed from both ends. |
Technical Details
| JavaScript Version: | ECMAScript 5 |
|---|
More Examples
Examples
If your browser does not support the trim() method, you can use a regular expression to achieve the same result:
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
function myFunction() {
var str = myTrim(" Example ");
alert(str);
}
Output:
Example
Try it yourself »
Other Extensions
JavaScript String Object