user3354912 user3354912 - 3 months ago 15
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 (: )
and
the end of the text string
.

How should I turn
the beginning of the text string
into
<tr><td>
,
colon+space
into
:</td><td>
and
the end of the text string
into
</td></tr>
?

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

With optional
<table id="newborn_table"><tbody>
and
</tbody></table>
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

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] +
    '</td></tr>'
});
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

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