一、trim
trim方法可以移除字符串前后两端的空白字符。
语法:str.trim()
返回值:返回一个移除原字符串头尾空白字符的新字符串,不会改变原字符串
const str = ' hello word '
console.log('@' + str.trim() + '@') // @hello word@
二、trimStart
trimStart方法可以移除字符串头部的空白字符。
语法:str.trimStart()
返回值:移除原字符串头部空白字符后的新字符串,不会改变原字符串
const str = ' hello word '
console.log('@' + str.trimStart() + '@') // @hello word @
二、trimEnd
trimEnd方法可以移除字符串尾部的空白字符。
语法:str.trimEnd()
返回值:移除原字符串尾部空白字符后的新字符串,不会改变原字符串
const str = ' hello word '
console.log('@' + str.trimEnd() + '@') // @ hello word@
总结
本文仅仅介绍了这三个方法的简单使用,它们也只是对字符串的前后空白字符做移除操作。如果想要对字符串中间的空格进行移除可能需要正则或者其他的一些方法。另外,trimStart有个别名是trimLeft,trimEnd有个别名是trimRight。