CSV Table to text table

by Alexey Demin

HTML

<div>
  <p>CSV input:</p>
  <textarea id="csv">Events table;;
Window Event Attributes;;
Events triggered for the window object (applies to the body tag):;;
Attribute;Value;Description
onafterprint;script;Script to be run after the document is printed
onbeforeprint;script;Script to be run before the document is printed
onbeforeunload;script;Script to be run when the document is about to be unloaded
onerror;script;Script to be run when an error occurs
onhashchange;script;Script to be run when there has been changes to the anchor part of the a URL</textarea>
  <button id="parse">Parse</button>
  <p>CSV output:</p>
  <textarea id="output"></textarea>
</div>

CSS

* {
  margin: 0;
  padding: 0;
}

div {
  padding: 5px;
}

textarea {
  width: 100%;
}

JavaScript

console.clear();

var lineSep = "\n",
  cellSep = ";",
  corner = "+",
  valSep = "|",
  lineStr = "-",
  cols = 0,
  colsLen = [],
  data = [],
  mergeCells = true,
  $ = function(id) {
    return document.getElementById(id);
  },
  /*
  str_pad('test', 30, '-=', 'LEFT');
	// -=-=-=-=-=-=-=-=-=-=-=-=-=test
  str_pad('test', 30, '-=', 'BOTH');
	// -------------test-------------
  */
  str_pad = function(input, pad_length, pad_string, pad_type) {

    var half = '',
      pad_to_go, str_pad_repeater = function(s, len) {
        var collect = '',
          i;
        while (collect.length < len) {
          collect += s;
        }
        return collect.substr(0, len);
      };

    if (pad_type != 'LEFT' && pad_type != 'RIGHT' && pad_type != 'BOTH') {
      pad_type = 'RIGHT';
    }
    if ((pad_to_go = pad_length - input.length) > 0) {
      if (pad_type == 'LEFT') {
        input = str_pad_repeater(pad_string, pad_to_go) + input;
      } else if (pad_type == 'RIGHT') {
        input = input + str_pad_repeater(pad_string, pad_to_go);
      } else if (pad_type == 'BOTH') {
        half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
        input = half + input + half;
        input = input.substr(0, pad_length);
      }
    }

    return input;
  };

$("parse").addEventListener("click", function(ev) {

  var csv = $("csv").value;
  var lines = csv.split(lineSep);

  // Обрабатываем каждую строку
  for (var i = 0; i < lines.length; i++) {

    // Разбиваем строку по разделителю
    var cells = lines[i].split(cellSep);

    // Сохраняем максимальное количество столбцов
    if (cells.length > cols) {
      cols = cells.length;
    }

    // Обрабатываем каждую ячейку
    for (var ii = 0; ii < cells.length; ii++) {
      var colLen = colsLen[ii] || 0;
      if (colLen < cells[ii].length) {
        colsLen[ii] = cells[ii].length;
      }
      data[i] = data[i] || [];
      data[i][ii] = cells[ii];
    }

  }
  var maxLineLen = colsLen.reduce(function(a, b)...