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 »
The trim()
method removes whitespace from both sides of a string.
The trim()
method does not change the original string.
string.trim()
NONE |
Type | Description |
A string | A string with removed whitespace from both ends. |
trim()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!