-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtable-converter.js
76 lines (64 loc) · 1.77 KB
/
table-converter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var NL = "\n";
var textarea, button, result, processor;
function setup() {
textarea = doc('pastebox');
button = doc('convert');
result = doc('result');
processor = doc('processor');
button.addEventListener('click', function() {
convertTable();
});
}
function doc(id) {
return document.getElementById(id) || document.getElementsByTagName(id)[0];
}
function convertTable() {
var content = textarea.value;
processor.innerHTML = content.replace(/\s+/g, ' ');
var tables = processor.getElementsByTagName('table');
var markdownResults = '';
if(tables) {
for(let e of tables) {
var markdownTable = convertTableElementToMarkdown(e);
markdownResults += markdownTable + NL + NL;
}
reportResult(tables.length + ' tables found. ' + NL + NL + markdownResults);
}
else {
reportResult('No table found');
}
}
function reportResult(message) {
result.innerHTML = message;
}
function convertTableElementToMarkdown(tableEl) {
var rows = [];
var trEls = tableEl.getElementsByTagName('tr');
for(var i=0; i<trEls.length; i++) {
var tableRow = trEls[i];
var markdownRow = convertTableRowElementToMarkdown(tableRow, i);
rows.push(markdownRow);
}
return rows.join(NL);
}
function convertTableRowElementToMarkdown(tableRowEl, rowNumber) {
var cells = [];
var cellEls = tableRowEl.children;
for(var i=0; i<cellEls.length; i++) {
var cell = cellEls[i];
cells.push(cell.innerText + ' |');
}
var row = '| ' + cells.join(" ");
if(rowNumber == 0) {
row = row + NL + createMarkdownDividerRow(cellEls.length);
}
return row;
}
function createMarkdownDividerRow(cellCount) {
var dividerCells = [];
for(i = 0; i<cellCount; i++) {
dividerCells.push('---' + ' |');
}
return '| ' + dividerCells.join(" ");
}
setup();