CSV files (short for Comma-Seperated Values) are a great way to exchange tabular data in a plain text file.
This is what it might look like:
The first row of this file is called the header, telling us what each column is about. The rest of the rows are just data.
First, we need to separte the rows. Regular Expressions are a great way to do that!
Simply split the string at an end of line delimiter (\r\n for Windows, \n for most other operating systems). By filtering the result we make sure we don’t end up with empty entries.
To extract the headers, we just get the first line and split it at the delimiter (usually a comma).
By calling `splice` on the `lines` array we also remove this first line from the result-set, thus making the next part easier.
The regular expression we use to extract the values is quite complex. I encourage you to dissect it using an online regex tool like regex101. You ready? Here comes:
It checks two cases: quoted values and unquoted values. Unquoted values are just regular values. Quoted values are surrounded by double quotes and may even contain additional “double double quotes” (sounds stupid, but is just an encoded single double quote – which sounds even more stupid…).
Using this Regular Expression gives us all the values in a single line. We then add the corresponding header-key and create neat little object.