1.使用 js 提供的函数 trim()
- trim() 方法会删除一个字符串两端的空白字符。
- trim() 方法并不影响原字符串本身,它返回的是一个新的字符串。
//trim()例子
let str = ' hello '
console.log(str.trim()) //hello
2.使用正则表达式
-
去除所有空格:
str = str.replace(/\s+/g,"")
-
去除两头空格:
str = str.replace(/^\s+|\s+$/g,"")
-
去除左空格:
str=str.replace( /^\s/, '')
-
去除右空格:
str=str.replace(/(\s$)/g, "")