String.prototype.trim()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
String
的 trim()
方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。
要返回一个仅从一端修剪空白字符的新字符串,请使用 trimStart()
或 trimEnd()
。
尝试一下
const greeting = " Hello world! ";
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trim());
// Expected output: "Hello world!";
语法
js
trim()
返回值
示例
使用 trim()
下面的示例从 str
的两端去除空白字符:
js
const str = " foo ";
console.log(str.trim()); // 'foo'
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-string.prototype.trim |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
trim |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.