JavaScript trim() Method
Example
Remove whitespace from both ends of a string:
var str = " ";
alert(str.trim());
Output:
Definition and Usage
The trim() method removes whitespace from both ends of a string. Whitespace includes spaces, tabs, line breaks, and other whitespace characters.
The trim() method does not change the original string.
The trim() method is not applicable to null, undefined, or Number types.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
| Method | |||||
|---|---|---|---|---|---|
| trim() | 10.0 | 9.0 | 3.5 | 5.0 | 10.5 |
Syntax
string.trim()
Parameters
None.
Return Value
| Type | Description |
|---|---|
| String | Returns the string with whitespace removed from both ends. |
Technical Details
| JavaScript Version: | ECMAScript 5 |
More Examples
Example
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(" ");
alert(str);
}
Output:
YouTip