1

since "this,is,a,comma,separated,sentence".split(","); will output

["this", "is", "a", "comma", "separated", "sentence"]

Then why "1000010001001".split("1") splitting not working as expected i.e ["0000", "000", "00"]. Instead it outputs

["", "0000", "000", "00", ""]
Sandeep Sihari
  • 97
  • 2
  • 14

1 Answers1

3

When the substrings to be split on exist on the edges of the string, or exist consecutively in the string, the empty string will be the result in those positions.

Given n substrings to split on in the string, the result will always contain n + 1 strings as a result.

For example:

aba

when split on a, will produce

['', 'b', '']

because '' + 'a' + 'b' + 'a' + '' is equivalent to the original string of aba.

1000010001001 works the same way.

1000010001001
^    ^   ^  ^
'' + '1' + '0000' + '1' + '000' + '1' + '00' + '1' + ''

An example with consecutive substrings to be split on, which the exact same logic applies to:

console.log('abba'.split('b'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It is also documented as such: `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.` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#parameters – Beyers Mar 23 '21 at 19:05