Reputation: 1726
I have table structure in HTML. I need to replace <tr>
with /n
and <td>
with '/t' using regex. What I have done is as follows:
var dataval = [].slice.call($("#printdiv").find("table tr")).map(function(row){
var a = row.textContent.trim().replace(/td/gi,"\t");
return a;
}).join("\r\n");
It is working partially but tab
is not coming between <td>
.
Upvotes: 0
Views: 567
Reputation: 337656
Firstly, never use RegEx to parse HTML. Secondly you can achieve this by building an 2d array represent all the tr
and td
elements in your table, like this:
var tableData = $('table tr').map(function() {
return [$(this).find('td').map(function() {
return $(this).text();
}).get()];
}).get();
Note that the returned value of the second map()
call needs to be placed in another array as jQuery annoyingly flattens out the first child array in the response of map()
.
From there you can build a string with each cell delimited with a tab, and each row with a new line. Something like this:
var output = '';
$.each(tableData, function(i, row) {
$.each(row, function(i, cell) {
output += cell + '\t';
})
output += '\n';
})
Upvotes: 2