Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading