JavaScript去除首尾空格

25 次浏览 1 分钟阅读 0 个喜欢

不管在哪种语言中去除字符串首尾空格都是会经常用到的

JavaScript中我们经常用的去除首尾空格方式是替换,比如:

str = '   hello world   '
console.log(str.replace(/^\s+|\s+$/g, '')) // hello world

而如今ES10将会让我们更加方便的去除空格

console.log(str.trimStart())

console.log(str.trimEnd())

屏幕快照 2019-11-26 下午6.41.33.png

JavaScript此外还提供了str.trimStart()的别名 str.trimLeft()

还有str.trimEnd()的别名 str.trimRight()