Home > front end >  Single CSV column is using multiple columns in HTML table
Single CSV column is using multiple columns in HTML table

Time:05-05

After a long journey to figure out how to load .csv files into a table I've run into another issue. One of the columns in my .csv file is splitting into other columns in my HTML table.

Part of the issue was with the file itself, where the content was actually split into other columns. After fixing everything (I left one on purpose), I'm still facing the same problem. It doesn't seem to be a character limit issue as they split after random words each time.

enter image description here

enter image description here

The very first entry in the .csv file is an easy example of what's going on. It also isn't everything in that column. The table is being read in through ajax and jQuery with the following code:


$(document).ready(function(){
    $('#file').click(function(){
     $.ajax({
      url:"014 - Dark Beginning 1 2004.csv",
      dataType:"text",
      success:function(data)
      {
       var card_data = data.split(/\r?\n|\r/);
       var table_data = '<table >';
       for(var count = 0; count<card_data.length; count  )
       {
        var cell_data = card_data[count].split(",");
        table_data  = '<tr>';
        for(var cell_count=0; cell_count<cell_data.length; cell_count  ){
         if(count === 0){
          table_data  = '<th>' cell_data[cell_count] '</th>';}
            else{
          table_data  = '<td>' cell_data[cell_count] '</td>';}
        }
        table_data  = '</tr>';
       }
       table_data  = '</table>';
       $('#card_table').html(table_data);
      }
     });
    });
    
   });

Is this some limit tables innately have or some other issue entirely? I have very minimally changed the CSS for the table solely to make it easier for me to look at for when I get to organizing the page layout.

CodePudding user response:

Since you're just splitting the comma string values by comma (,) you're splitting the strings in your descriptions values as well. In a csv file, values that might contain the separator (, in this case) or other special caracters are wrapped by quotes "", in your case in the descriptions. You must not account for any comma that might reside inside a quoted string, as everything written inside account for a single value of a collumn row.

I would suggest using a library, such as csv-parser to handle this kind of parsing, as those kind of tasks might take a lot of details into account that you might not want to be troubled with.

  • Related