JavaScript去除字符串空格
replace正则匹配方法
- 去除字符串内所有的空格:
str = str.replace(/\s*/g,""); - 去除字符串内两头的空格:
str = str.replace(/^\s*|\s*$/g,""); - 去除字符串内左侧的空格:
str = str.replace(/^\s*/,""); - 去除字符串内右侧的空格:
str = str.replace(/(\s*$)/g,"")
1 | |
str.trim()方法
str.trim()
trim() 方法是用来删除字符串两端的空白字符并返回,trim 方法并不影响原来的字符串本身,它返回的是一个新的字符串。
缺点:只能去除字符串两端的空格,不能去除中间的空格
1 | |
str.trimLeft()
单独去除左侧空格则使用
1 | |
str.trimRight()
单独去除右侧空格则使用
1 | |
JavaScript去除字符串空格
http://xiaodongxier.github.io/pages/beeb254e.html