I'm questioning why I got the following output from this code:
'Willie'.split(/[i-l]{1}/); // [ 'W', '', '', '', 'e' ]
I was expecting to get ['W', 'e']. I'm not sure why it's inserting holes in the array.
You are splitting on single letter, so each illi is considered as a separator, and the string splits as follows:
w i l l i e
# w "" "" "" e
# if there's no content between separators, an empty string is in place
# or what would you get with a csv string w,,,,e split on comma ?
Try using a greedy quantifier + which will match the pattern as long as it can, so illi is considered as one separator:
console.log('Willie'.split(/[i-l]+/));
You are splitting the Willie string by i, j, k, l characters. If il substring appears, and both i and l are separators, between those letters there is an empty string - which is counted in the result.
Let's analyze whole string:
'W', '', 'i', '', 'l', '', 'l', '', 'i', '', 'e'
Then split it by i and l:
('W', ''), /i separator/, '', /l separator/, '', /l separator/, '', /i separator/, ('', 'e')
so after concatenation groups we get:
'W', '', '', '', 'e'
'' instances. I expect all 5 of those empty strings '' to appear in the array now. Could you explain why the first and last set of '' were bound to the letters 'W' and 'e' respectively?('W' '') and ('', 'e') are before/after separators so they are counted as a one substrings.'' substrings that I'm not understanding. Could you link to any links or documents?