有一次做CodeWars上面的题目时,需要发现split()实现结果和我想的不一样:
//想要把'hello world'转换成'helloworld'
const str = 'hello world'; //中间有三个空格 const arr = str.split(' '); //一个空格 console.log(arr.join(''));
结果是:
["hello", "", "", "world"]
数组里会有空字符串。
查看MDN文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/split#Syntax
分割方法:
The
split()
method divides aString
into an ordered list of substrings, puts these substrings into an array, and returns the array.
如果分隔符出现在开头或者结尾,会返回一个空字符串""
- If
separator
appears at the beginning (or end) of the string, it still has the effect of splitting. The result is an empty (i.e. zero length) string, which appears at the first (or last) position of the returned array.
例如:
const str = 'aqwrew'; const words = str.split('a'); console.log(words);
对于这种题目,推荐另一种做法:
//想要把'hello world'转换成'helloworld' const str = 'hello world'; //中间有三个空格 const arr = str.trim().split(/s+/));
console.log(arr.join(''));