【随笔】当split()匹配的字符串出现在开头或者结尾时会返回什么样的结果?

有一次做CodeWars上面的题目时,需要发现split()实现结果和我想的不一样:

//想要把'hello   world'转换成'helloworld'
const str = 'hello world'; //中间有三个空格 const arr = str.split(' '); //以一个空格作为分隔符 console.log(arr); //["hello", "", "", "world"]

数组里会有空字符串。

查看MDN文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/split#Syntax

分割方法:

The split() method divides a String 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 arr = str.split('a');
console.log(arr);           //["", "qwrew"]

 

对于这种题目,推荐另一种做法:

//想要把'hello   world'转换成'helloworld'
const str = 'hello   world';      //中间有三个空格
const arr = str.trim().split(/\s+/));

console.log(arr.join(''));

 

posted @ 2020-10-15 15:58  bcj7wi3kd5h1wd6  阅读(258)  评论(0编辑  收藏  举报