.trim() 是字符串的原生方法:去掉字符串首尾两端的空白字符,返回一个新字符串。空白包括空格、制表符 \t、换行 \n、回车 \r 等。
核心特点
只处理两端,中间的空白不动
返回新字符串,原字符串不变(字符串在 JS/TS 里是不可变的)
- snippet.javascript
const s = " hello world "; s.trim(); // "hello world" // 中间的空白保留 " a b ".trim(); // "a b" // 各种空白字符都能去 "\n\t hi \r\n".trim(); // "hi"