使用非常相似的正则表达式分割字符串后,输出结果截然不同

时间:2019-06-11 03:11:53

标签: javascript regex split

我玩弄了一些代码,然后遇到了奇怪的行为。您能告诉我为什么这些表达式产生不同的输出吗?

const a = 'abcd';

const b = a.split(/\b|\B/);
console.log('b: ', b);

const c = a.split(/(\b|\B)/);
console.log('c: ', c);

const d = a.split(/(\b|\B){0}/);
console.log('d: ', d);

const e = a.split(/(\b|\B)(?=(\b|\B){0})/);
console.log('e: ', e);

const f = a.split(/(\b|\B){0}(?=(\b|\B){0})/);
console.log('f: ', f);

输出为:

b:  [ 'a', 'b', 'c', 'd' ] 
 
c:  [ 'a', '', 'b', '', 'c', '', 'd' ] 
 
d:  [ 'a', undefined, 'b', undefined, 'c', undefined, 'd' ] 
 
e:  [ 'a', '', undefined, 'b', '', undefined, 'c', '', undefined, 'd' ]

f:  [ 'a', 
  undefined, 
  undefined, 
  'b', 
  undefined, 
  undefined, 
  'c', 
  undefined, 
  undefined, 
  'd' ]

1 个答案:

答案 0 :(得分:1)

来自ECMA

  

String.prototype.split(分隔符,限制)

     

如果分隔符是包含捕获括号的正则表达式,则每次将分隔符匹配时,捕获括号的结果(包括任何未定义的结果)都会被拼接到输出数组中。

每个示例c,d,e和f中,捕获组的结果都被拼接成结果数组。