Search code examples
javascripthtmldatatableplaintext

How to get an html table out of a plain text table


I have some data stored in plain text files. It uses spaces to seperate the different columns but in different tables the columns have a different width (different number of characters). The content of the table data includes words, integers, floats and ranges.

Is the a simple way to extract the data in javascript and transpile it into an html table? I would prefer a kind of general approach that can be used for all tables (means it had to detect the position of a new column by itself - fixed indexes are impossible because as previously mentioned they differ from file to file).

Here is an example how one of these plain text tables look like:

Line1    23     45.4     12 - 14
Line2    4      5.9      < 8
Line3    13.56  105.34   20.37 - 130.20
Line4    7.2    14.2     10.1 - 14.0
...

Solution

  • I think this guy here has the right solution for you.

    He's splitting up his lines on the basis of spaces.

    So once you get your data in an array, you can simply loop through the arrays and append string with html tags to form a html table. You can refer to the displayHtml() method in peeto's answer.

    Let me know you need further help with it.

    EDIT **

    So, as per your sample data you provided, I'm assuming two or more spaces to change to a new column. If this is the way you can try my code below.

    var data = `23     45.4     12 - 14
    4      5.9      < 8
    13.56  105.34   20.37 - 130.20
    7.2    14.2     10.1 - 14.0`;
    
    data = data.split(/\r?\n/); // split text into lines
    
    var lines = [];
    for (var i = 0; i < data.length; i++) {
      data[i] = data[i].trim();
      lines.push(data[i].split(/[ ][ ]+/)); // split lines further based on 2 or more spaces
    }
    // creating html string
    var htmlStr = '<table id=\'myTable\'>';
    for (var i = 0; i < lines.length; i++) {
      htmlStr += '<tr>';
      for (var j = 0; j < lines[i].length; j++) {
        htmlStr += '<td>' + lines[i][j] + '</td>';
      }
      htmlStr += '</tr>';
    }
    htmlStr += '</table>';
    
    document.getElementById('myDiv').innerHTML = htmlStr; // append string wherever you like
    

    I hope this helps you. But if it still doesn't, you really need to have a close look on all your files and find at least one similarity between them about the pattern being followed to change the column.