rene rene - 7 months ago 12
Javascript Question

Align text on \t, colon and \t

I have the following raw text that I wrap in a

<pre>
tag to salvage as much of the layout as possible:



<pre>

test

field 1 : Foo
longer field 2 : Bar
very long field 3 : FooBar

other text and values

</pre>


The field and values are separated by a tab char (\t) a colon and a tab char(\t).

I would like to align the colons so the rendered result would be:

test

field 1 : Foo
longer field 2 : Bar
very long field 3 : FooBar

other text and values


You'll find a jsfiddle here with my effort so far.

I don't have much control over the text but I tried to replace the \t:\t with a
<span>
so I get some control with css styling but so far not much joy.

This is the javascript I use to replace the \t:\t with a span:

$('pre').html(
$('pre')
.html()
.split('\t:\t')
.join('<span class="tab">&nbsp;:&nbsp;</span>'));


and added this css rule to float the
<span>
but that



.tab {
background-color:red;
width: 10em;
display: inline-block;
text-align: right;
float: left;
}


renders the
span
at the start of each new line. I've tried also
position: absolute
to no avail.

What are my options to get the colons aligned?

Answer

Using CSS as the primary driver:

$(document).ready(function() {
    $('pre').html(
        $('pre')
        .html()
        .replace(/(.*)\t:\t(.*)/g,function(_,key,value) {
            return '<div class="row">'+
                '<span class="col">'+key+'</span>'+
                '<span class="col"> : </span>'+
                '<span class="col">'+value+'</span>'+
            '</div>';
        })
    );
});
pre {display:table}
.row {display:table-row}
.col {display:table-cell}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre>
    
    test
    
    field 1	:	Foo
    longer field 2	:	Bar
    very long field 3 	:	FooBar
    
    other text and values
    
    </pre>

The important thing here is that the JavaScript will scan for lines of the required format (key[tab]:[tab]value) and dress them up in suitable elements. The CSS then makes them uniform.