去除空白:trim()、trimStart()、trimEnd()
...大约 1 分钟
在ES6中,我们可以使用trim()、trimStart()和trimEnd()这3种方法来去除字符串首尾的空空格。
语法
str.trim()
str.trimStart()
str.trimEnd()
说明
trim()用于同时去除字符串首尾的空格,
trimStart()用于去除字符串开始处的空格,
trimEnd()用于去除字符串结尾处的空格。
此外,这3种方法最后都会返回去除空格后的字符串。
示例
const str = ' shan '
const result1 = str.trim()
console.log(result1.length)
const result2 = str.trimStart()
console.log(result2.length)
const result3 = str.trimEnd()
console.log(result3.length)
>>> 4
>>> 8
>>> 6
分析
在这个例子中,str的开始处有2个空格,结尾处有4个空格,小伙伴们可以自行算一下用不同方法去除空格后的字符串长度,检验输出结果。
去除字符串的首尾空格,在实际开发中是非常有用的。在前后端交互时,后端传过来的数据经常有空格,而我们前端需要把这些空格去除,这样得到的才是想要的数据。还有一种情况是在做验证码校验时,我们通常需要去掉用户输入字符的首尾空格,再传递给后端。
