table tab-to-spaces convert

Convert a tab-separated table string into space separated table string, keeping the columns aligned.

by Laurens Maneschijn

HTML

Convert a tab-separated table string into space separated table string, keeping the columns aligned.<br>
(especially useful to select text from a website table, and then convert it into simple textfile monospace format)<br>
<hr>
In:
<textarea id="ta1" placeholder="paste table string with tabs here"></textarea>
Out:
<textarea id="ta2" placeholder="spaces only string appears here"></textarea>

CSS

textarea {
	box-sizing: border-box;
	width: 100%;
	height: 200px;
	tab-size: 4;
	white-space: pre;
}

/*
Attempt to make whitespace (spaces and tabs) more visible:
Not sure how to do this css only, and not much look on google...most are JS solutions replacing text.
semi-related: https://discourse.wicg.io/t/visualizing-whitespace-characters/1394

textarea:hover {
	text-decoration: underline;
}
*/

JavaScript

$(document).on('change keyup paste', '#ta1', function(e){
	$('#ta2').val(
		convert(
			$('#ta1').val()
		)
	);
});

function convert(str1) {
	// assume columns are seperated by a '\t':
	var str, lines, cols, lines_cols, maxcolwidths, col_separator = '\t', line_separator = '\n';
	lines = str1.split(line_separator);
	maxcolwidths = [];
	lines_cols = [];
	lines.forEach(function(line, line_i) {
		cols = line.split(col_separator);
		cols.forEach(function(col, col_i) {
			if (maxcolwidths[col_i] === undefined) {
				maxcolwidths[col_i] = 0;
			}
			maxcolwidths[col_i] = Math.max(maxcolwidths[col_i], col.length);
			if (lines_cols[line_i] === undefined) {
				lines_cols[line_i] = [];
			}
			lines_cols[line_i][col_i] = col;
		});
	});
	str = '';
	lines_cols.forEach(function(line, line_i) {
		line.forEach(function(col, col_i) {
			// TODO: str append slow when done often and for long strings
			// replace with [] and .join('')
//			str += col + '\t';	// identical to input
			str += fix(col, maxcolwidths[col_i]) + ' ';
		});
		str += '\n';
	});
	return str;
}

function fix(str, n) {
	// dumb but usually enough:
	return (str + '                                                            ').substr(0, n);
}

/*
	TODO:
	- optional input colseparator (instead of \t)
	- optional ouput colseperator (instead of ' ')
	- optional padding for last column
	- fix padding for any col size and not hardcoded max 60 spaces
*/


/*
	To quite simply convert any basic* table grid to a safe string :
	(basic: without colspan=>1 rowspan=>1 elements)

	var targettable = $('#targattable');
	var s = '';
	$(targettable).find('tr').each(function(i,tr){
	  $(tr).find('td,th').each(function(i,td){
	    // note: strip (replace) any whitespace newlines (or other repeated whitespace):
		// (especially newlines in table cells often cause havoc in selected text output)
		s += $.trim($(td).text().replace(/\s+/g, ' '));
		s += '\t';
	  });
	  s += '\n';
	});
	console.log(s);

	// tip: inspect table element...