CSV to HTML translation: Difference between revisions

Content added Content deleted
(updating js example)
Line 1,362: Line 1,362:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{output?|JavaScript}}
<lang JavaScript>
<lang JavaScript>
var csv = "Character,Speech\n" +
var csv = "Character,Speech\n" +
Line 1,371: Line 1,370:
"The multitude,Behold his mother! Behold his mother!";
"The multitude,Behold his mother! Behold his mother!";


csv.replace(/&/g, '&amp;')
csv = csv.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
.replace(/"/g, '&quot;');


var lines = csv.split(/[\n\r]+/g),
var lines = csv.split(/[\n\r]+/g),
Line 1,380: Line 1,379:
line,
line,
rows = "",
rows = "",
thead = '<thead>'+
thead = '<tr>'+
'<th>'+header[0]+'</th>'+
'<th>'+header[0]+'</th>'+
'<th>'+header[1]+'</th>'+
'<th>'+header[1]+'</th>'+
'</thead>';
'</tr>\n';


for (var i=0, len=lines.length; i<len; i++) {
for (var i=0, len=lines.length; i<len; i++) {
Line 1,390: Line 1,389:
'<td>'+line[0]+'</td>'+
'<td>'+line[0]+'</td>'+
'<td>'+line[1]+'</td>'+
'<td>'+line[1]+'</td>'+
'</tr>';
'</tr>\n';
}
}


console.log('<table>' + thead + '<tbody>' + rows + '</tbody></table>' );
console.log('<table><thead>\n' + thead + '</thead><tbody>\n' + rows + '</tbody></table>' );
</lang>

<lang html>
<table><thead>
<tr><th>Character</th><th>Speech</th></tr>
</thead><tbody>
<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>
<tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr>
<tr><td>The multitude</td><td>Who are you?</td></tr>
<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>
<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>
</tbody></table>
</lang>
</lang>