Skip to content
Advertisement

Why does using a String.split(regex) include an empty string at the beginning of resulting array?

I have a string data that is a numbered list (e.g. "1.Line 1n2. Line 2nLine 2 Continuedn3. Line 3") I tried making a regex that splits the string into ["Line 1n", "Line 2nLine 2 Continuedn", "Line 3"] and I made this regex const reg = /d+./gm. When I use the following regex via data.split(reg), I do see the elements in the desired output, but I also see a leading "" element in the beginning of the array – ["","Line 1n", "Line 2nLine 2 Continuedn", "Line 3"]. Any explanation as to why this "" exists? Any way to prevent this from showing besides just slicing the array, or even the proper regex if this one is wrong.

Advertisement

Answer

Your initial empty string exists because your split applies also to the first number 1 "1.Line 1n, which will separate everything after your regex (Like 1n) from anything before ("").

In order to fix this problem, you can try making your regex more specific, so that it will apply the split beginning from the second line. One way of doing this is adding up the n to the regex (which can be found only from the second line on as needed).

const reg = \n/d+./gm
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement