0

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>.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Santhucool
  • 1,656
  • 2
  • 36
  • 92

1 Answers1

2

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';
})

Working example

Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339