user3354912 user3354912 - 1 year ago 69
Javascript Question

Turn several strings of structured text into HTML table

For example I have the following text with no tags at all within the HTML page:

Color: red
Shape: square
Side: 1mm

As much rows as needed, but three is quite enough for this question. Even one would be.

In those rows I'll always have
the beginning of the text string
colon+space (: )
the end of the text string

How should I turn
the beginning of the text string
the end of the text string

May be it would be more correct to turn only the first colon within the text string into
instead of all
and get rid of the following
, I'm just afraid to turn this hopefully trivial question into more complicated one with no reason.

With optional
<table id="newborn_table"><tbody>
at the very beginning and the very end of the whole resulting construction respectively. Optional - because I could insert those tags around the placeholder for the table cells within the page. But I think the script wouldn't be finished without opener and closer for the newborn table. :)

I am looking to implement a pure JavaScript solution without jQuery if possible.

PS: I already see it is quite possible as my improvised sample table becomes colored as soon as I click anywhere outside of the message field! :)

Answer Source

The original text here has some extra unnecessary lines before and after the text to demonstrate the need for dealing with, and the ability to deal with, extra lines.

var opening = '<table id="newborn_table"><tbody>';
var closing = '</tbody></table>';
var origText = document.querySelector('#source').innerText;
var lines = origText.split('\n').filter(function(line) {
  return (line !== "");
var rowsText = '';
lines.forEach(function(line) {
  var parts = line.split(': ');
  rowsText +=
    '<tr><td>' +
    parts[0] +
    '</td><td>' +
    parts[1] +
document.querySelector('#result').innerHTML =
  opening + rowsText + closing;
#newborn_table td {
  border: solid red 1px;
<p>Original text:<p>
<pre id="source">

Color: red
Shape: square
Side: 1mm

<p>Parsed table:</p>
<div id="result"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download