Andrei Kovalev
Andrei Kovalev

Reputation: 959

Weirdly different output after splitting string with very similar regular expressions

I played around with some code and ran into strange behaving of it. Can you explain to me why these expressions produce different outputs?

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);

The output is:

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' ]

Upvotes: 0

Views: 32

Answers (1)

Icehorn
Icehorn

Reputation: 1337

From ECMA:

String.prototype.split (separator, limit)

If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array.

The results from the capture groups are being spliced into the resulting array in each of your examples c, d, e, and f

Upvotes: 1

Related Questions