JavaScript去除字符串空格

replace正则匹配方法

  • 去除字符串内所有的空格:str = str.replace(/\s*/g,"");
  • 去除字符串内两头的空格:str = str.replace(/^\s*|\s*$/g,"");
  • 去除字符串内左侧的空格:str = str.replace(/^\s*/,"");
  • 去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,"")
1
2
3
4
5
let str = " 这 是 测 试 内 容 "
console.log('str.replace(/\s*/g,"") 去除所有-->', str.replace(/\s*/g,"") ) // "这是测试内容"
console.log('str.replace(/^\s*|\s*$/g,"") 去除两头-->', str.replace(/^\s*|\s*$/g,"") ) // "这 是 测 试 内 容"
console.log('str.replace(/^\s*/,"") 去除左侧->', str.replace(/^\s*/,"") ) // "这 是 测 试 内 容 "
console.log('str.replace(/(\s*$)/g,"") 去除右侧-->', str.replace(/(\s*$)/g,"") ) //" 这 是 测 试 内 容"

str.trim()方法

str.trim()

trim() 方法是用来删除字符串两端的空白字符并返回,trim 方法并不影响原来的字符串本身,它返回的是一个新的字符串。
缺点:只能去除字符串两端的空格,不能去除中间的空格

1
2
let str = " 这 是 测 试 内 容 "
console.log('str.trim() 去除两头-->', str.trim() ) // "这 是 测 试 内 容"

str.trimLeft()

单独去除左侧空格则使用

1
2
let str = " 这 是 测 试 内 容 "
console.log('str.trimLeft() 去除两头-->', str.trimLeft() ) // "这 是 测 试 内 容 "

str.trimRight()

单独去除右侧空格则使用

1
2
let str = " 这 是 测 试 内 容 "
console.log('str.trimRight() 去除两头-->', str.trimRight() ) // " 这 是 测 试 内 容"

JavaScript去除字符串空格
http://xiaodongxier.github.io/pages/beeb254e.html
作者
WangYongJie
发布于
2023年8月26日
更新于
2023年9月9日
许可协议