JavaScript String trim()
Example 1
Remove spaces with trim():
let text = " Hello World! ";
let result = text.trim();
Try it Yourself »
Remove spaces with replace() using a regular expression:
let text = " Hello World! ";
let result = text.replace(/^\s+|\s+$/gm,'');
Try it Yourself »
Definition and Usage
The trim()
method removes whitespace from both sides of a string.
The trim()
method does not change the original string.
Syntax
string.trim()
Parameters
NONE |
Return Value
Type | Description |
A string | A string with removed whitespace from both ends. |
Browser Support
trim()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |