H5字符串去掉5种空格方案总结
1.需求背景
- 最近开发H5项目,在一些输入场景下是不需要字符串的空格的,因此要针对性做一些处理。
解决方案
-
// 方法如下:(默认去除所有) function strTrim(str, type = 'all') { if (!str) { return str } let newStr = '' switch (type) { case 'left': // 左 newStr = str.replace(/^\s*/g, '') break case 'right': // 右 newStr = str.replace(/\s*$/g, '') break case 'both': // 两边 newStr = str.replace(/^\s*|\s*$/g, '') break case 'center': // 中间 newStr = str.replace(/[ ]/g, '') break default: // 所有 newStr = str.replace(/\s+/g, '') } return newStr }
-
解决。