# 如何去除字符串首尾空白字符
更多描述
实现一个 trim 函数,如同原生的 Array.prototype.trim
,以下有两个测试用例
//=> hello
" hello ".trim();
//=> hello
" hello \t\n".trim();
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 667 (opens new window)
Author
在正则表达式中,\s
指匹配一个空白字符,包括空格、制表符、换页符和换行符。等价于[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
。
const trim = (str) => str.trim || str.replace(/^\s+|\s+$/g, "");
Author
function trim(str = "") {
str = String(str);
let left = 0;
let right = str.length - 1;
while (/\s/.test(str[left]) && left < right) {
left += 1;
}
while (/\s/.test(str[right]) && left < right) {
right -= 1;
}
return str.slice(left, right + 1);
}
Author
const trim = (str) => str.trim || str.replace(/^\s+|\s+$/g, "");
const trim = str => str.trim?.() || str.replace(/^\s+|\s+$/g, '')