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

Time:08-03

I have a string data that is a numbered list (e.g. "1.Line 1\n2. Line 2\nLine 2 Continued\n3. Line 3") I tried making a regex that splits the string into ["Line 1\n", "Line 2\nLine 2 Continued\n", "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 1\n", "Line 2\nLine 2 Continued\n", "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.

CodePudding user response:

Your initial empty string exists because your split applies also to the first number 1 "1.Line 1\n, which will separate everything after your regex (Like 1\n) 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
  • Related