ES2019 对字符串实例新增了trimStart()和trimEnd()这两个方法。它们的行为与trim()一致,trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。
我们用函数的形式来实现以上方法:
/**
str:传入的字符串
direct:表示具体从哪边trim
*/
function trim(str, direct=null) {
if(direct === "l") { // left 表示去除 头部空格
return str.replace(/^\s+/g, "");
} else if(direct==="r") { // right 表示去除 尾部空格
return str.replace(/\s+$/g, "");
} else { // 去除两端空格
return str.replace(/(^\s+)|(\s+$)/g, "");
}
}
let str = " hello ";
trim(str) //hello/空格都去除了
trim(str, "l") //hello /右边空格还在
trim(str, "r") // hello/左边空格已不再