bloom berg
bloom berg

Reputation: 51

how to put in separator for textContent in javascript?

I'm trying to convert an html table to a csv file using javascript. I tried to loop through the table rows & get the textContent from it and then saved it in an array & then convert that array to csv. But when I get textContent I do not have any separators between two words.

E.g. if my html looks like this:

var ans = $("#my_table").find("table tr");

    <tr>
      <th>Test1</th>
      <th>Test2</th>
    </tr>

    <tr>
      <td> Current </td>
      <td> Next </td>
    </tr>

when I loop through <tr> I get the following output:

Test1Test2
CurrentNext

However there is no space or any separator. How can I put in a seperator while looping, since I have to save that in csv format?

Looking for this output:

Test1,Test2
Current,Next

My js code:

for(var i=0; i<ans.length; i++){
    console.log(ans[i].textContent);
}

Upvotes: 5

Views: 1307

Answers (4)

Malachi
Malachi

Reputation: 3221

You have to change the code that retrieves the rows and then go through each row worth of cells.

var ans = $("#my_table").rows;
var tableText;

for (var i = 0; i < ans.length; i++) {
    for (var j = 0; j < ans[i].cells.length; j++) {
        if (j == 0) {
            tableText += ans[i].cells[j].textContent;
        } else {
            tableText += "," + ans[i].cells[j].textContent;
        }
    }
    tableText += "\n";
}

console.log(tableText);

is one way that you could achieve those results, without having a trailing or preceding comma

Upvotes: 3

The Spooniest
The Spooniest

Reputation: 2873

There's no simple property for this, so you'll have to use a function or object of some kind.

Here's my attempt (fiddle). It weighs in a little heavier than the other answers, but attempts to escape some of the text per the standard (or as close to a standard as CSV has):

function CSVRenderer() {}

CSVRenderer.prototype.escape = function (s) {
    // Escape double-quotes
    if (s.indexOf('"') !== -1) {
        s = s.replace(/"/g, '""');
    }
    // Surround text with containing, commas, or double-quotes
    if (
    s.indexOf(',') !== -1 || s.indexOf('\n') !== -1 || s.indexOf('"') !== -1) {
        s = '"' + s + '"';
    }
    return s;
};

CSVRenderer.prototype.renderCell = function (cell) {
    return this.escape(cell.textContent);
};

CSVRenderer.prototype.renderRow = function (row) {
    return Array.prototype.map.call(
        row.cells,
        this.renderCell,
        this
    ).join(',');
};

CSVRenderer.prototype.render = function (table) {
    return Array.prototype.map.call(
        table.rows,
        this.renderRow,
        this
    ).join('\n');
};

You could use it something like this:

var renderer = new CSVRenderer();
var csv = renderer.render(document.getElementById("my_table"));

If for whatever reason you have multiple tables per page, you can reuse renderer for each one.

The version above does some basic escaping per the CSV format, in that it will handle commas, text newlines, and quotes correctly. It doesn't handle uneven row lengths, though, and it might be useful to make it convert <br> tags into newlines. But for the use cases you've mentioned here, it ought to get the job done.

Upvotes: 1

Sahil Ahuja
Sahil Ahuja

Reputation: 2493

Hope the following correction works:

var ans = $("#mytable").find("tr");
for (var i = 0; i < ans.length; i++) {
  var rows = ans[i].children;
  var rowText = "";
  for (var j = 0; j < rows.length; j++) {
    rowText += rows[j].textContent;  //.trim() if you want
    if (j < (rows.length - 1)) {
        rowText += ",";
      }
    }
  console.log(rowText);
}

Upvotes: -1

howderek
howderek

Reputation: 2244

I would suggest a solution that doesn't depend on external libraries:

function tableToCSV(table) {
    var output = [], i = 0, j = 0;
    for (i = 0; i < table.rows.length; i += 1) {
        var temp = [];
        for (j = 0; j < table.rows[i].cells.length; j += 1) {
            temp.push(table.rows[i].cells[j].innerText);
        }
        output.push(temp.join(','));
    }
    return output.join('\n');
}

//to access your table use tableToCSV(document.getElementById('my_table'));
//or with jQuery tableToCSV($('#my_table')[0]);

Example: http://jsfiddle.net/howderek/ejxqbyrm/

Upvotes: 2

Related Questions