trim 去除空格

trim 去除空格

trim(str, pos)

该方法可以去除空格,分别可以去除所有空格,两端空格,左边空格,右边空格,默认为去除两端空格

  • str 字符串

  • pos 去除那些位置的空格,可选为:both-默认值,去除两端空格,left-去除左边空格,right-去除右边空格,all-去除包括中间和两端的所有空格

1
2
3
4
import trim from 'trim.js'

console.log(trim('abc b ', 'all')) // 去除所有空格
console.log(trim(' abc ')) // 去除两端空格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function trim(str, pos = 'both') {
if (pos == 'both') {
return str.replace(/^\s+|\s+$/g, '')
} else if (pos == 'left') {
return str.replace(/^\s*/, '')
} else if (pos == 'right') {
return str.replace(/(\s*$)/g, '')
} else if (pos == 'all') {
return str.replace(/\s+/g, '')
} else {
return str
}
}

export default trim