CSV to Table Example

by Sergey Morozov

HTML

<textarea id="csvData">Name,Position,Age
Bob,Center,20
Joe,Left Wing,23
Mike,Goalie,31
Jeff,Right Wing,101
Nina,Defender,29

</textarea>
<p id="demo">

</p>

CSS

textarea { 
  display: none; 
}

td {
  border: thin black solid;
}

JavaScript

// Read CSV data from text area
var data = document.getElementById("csvData").value;
// Trasform it into array of lines trimming any new lines at the end
var lines = data.replace(/\n+$/, "").split("\n"),
    output = [];

// Iterate over each line
lines.forEach(function(line, index) {
	console.log(line);
  console.log(index);
  // very first row of the data would become table header row
	if(index === 0) {
  	output.push("<tr><th>" + line.split(",").join("</th><th>") + "</th></tr>");
  } else {
   // rest of the lines would be rows of the table 
   output.push("<tr><td>" + line.split(",").join("</td><td>") + "</td></tr>");
  }
});
// Wrap it all in table tags
output = "<table>" + output.join("") + "</table>";
// Append to demo paragraph for this example
document.getElementById("demo").innerHTML = output;

// For magic mirror getDom method you probably would end up just appending it to a wrapper and returning it like next 3 commented lines
// var wrapper = document.createElement("div");
// wrapper.innerHTML = output;
// return wrapper;