Convert comma separated string into HTML table

Hi,

I would like to have comma separated lists automatically convert into tables.

I’ve found this code online:

There is a link to the code in the answer:

If I populate the variable exampleCSV with the following data, I get a table as an output:

Case, Singular, Plural

Nominativ,das Kind, die Kinder

Genitiv,des Kindes, der Kinder

Dativ,dem Kind, den Kindern

Akkusativ,das Kind, die Kinder

The great thing about the code, it adjusts to your needs, so you can easily add more columns and rows.

Does anyone know how to make use of the code for Anki?

Thank you!

Here is a quick example of how to generate an HTML table from a comma-separated string. I’m not sure if this is what you are looking for, but I think at least this can be a starting point.

Template:

<div id="table-container"></div>

<script>
    function generateTableFromString(commaSepString) {
        const table = document.createElement('table');
        const thead = table.appendChild(document.createElement('thead'));
        const tbody = table.appendChild(document.createElement('tbody'));
        commaSepString.split('\n').forEach((line, index) => {
            let parent;
            let cellTag;
            if (index === 0) {
                parent = thead;
                cellTag = 'th';
            } else {
                parent = tbody;
                cellTag = 'td';
            }
            const tr = parent.appendChild(document.createElement('tr'));
            line.split(',').forEach((cell) => {
                const cellElement = tr.appendChild(document.createElement(cellTag));
                cellElement.appendChild(document.createTextNode(cell.trim()));
            });
        });
        return table;
    }

    // convert an HTML fragment to plain text
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = `{{Front}}`;
    document.documentElement.appendChild(tempDiv);
    var commaSepString = tempDiv.innerText;
    document.documentElement.removeChild(tempDiv);

    var table = generateTableFromString(commaSepString);
    document.querySelector('#table-container').appendChild(table);
</script>

Styling:

thead {
    background-color: saddlebrown;
}
td {
    border: 1px solid lightgreen;
}

Screenshot:

Also the following link may help you:

2 Likes

Hi hkr!
Thank you for your code.
Yes, this looks good!
This is what I needed.
Cheers

The code provided by hkr solved this case.

The following code (an alternative to hkr’s solution) leads in 3 steps to the solution.
step 1: convert an HTML fragment into plain text. If you skip this step, the code split(\n) won’t work, as Anki doesn’t recognize the input value as multiple line value and you’ll receive an error message.
step 2: convert comma separated string into JSON 2D array
step 3 : convert JSON 2D array into HTML table and append to ids #table_head and #table_content

<div>

<table>
  <thead>
    <tr id="table_head">
    </tr>
  </thead>
  <tbody id="table_content">

  </tbody>
</table>

</div>


<script src='_jquery.js'></script>
<script>

// step 1: convert an HTML fragment into plain text. If you skip this step, the code split(\n) won't work, as Anki doesn't recognize the input value as multiple line value and you'll receive an error message.

    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = '{{inflection}}';
    document.documentElement.appendChild(tempDiv);
    var commaSepString = tempDiv.innerText;
    document.documentElement.removeChild(tempDiv);

// step 2: convert comma separated string into JSON 2D array

		function csvJSON(csv) {
    const lines = csv.split('\n');
    const result = []
    const headers = lines[0].split(',')

    for (let i = 1; i < lines.length; i++) {        
        if (!lines[i])
            continue
        const obj = {}
        const currentline = lines[i].split(',')

        for (let j = 0; j < headers.length; j++) {
            obj[headers[j]] = currentline[j]
        }
        result.push(obj)
    }
    return result
}

const json = csvJSON(commaSepString)

// step 3 : convert JSON 2D array into HTML table and append to ids #table_head and #table_content
//code source: https://stackoverflow.com/questions/1051061/convert-json-array-to-an-html-table-in-jquery


// Get Table headers and print
for (var k = 0; k < Object.keys(json[0]).length; k++) {
  $('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');
}

// Get table body and print
for (var i = 0; i < Object.keys(json).length; i++) {
  $('#table_content').append('<tr>');
  for (var j = 0; j < Object.keys(json[0]).length; j++) {
    $('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');
  }
  $('#table_content').append('</tr>');
}

</script>