简体   繁体   English

如何在javascript中放入textContent的分隔符?

[英]how to put in separator for textContent in javascript?

I'm trying to convert an html table to a csv file using javascript. 我正在尝试使用javascript将html表转换为csv文件。 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. 我试图遍历表行并从中获取textContent ,然后将其保存在数组中,然后将该数组转换为csv。 But when I get textContent I do not have any separators between two words. 但是当我得到textContent时,我在两个单词之间没有任何分隔符。

Eg if my html looks like this: 例如,如果我的HTML看起来像这样:

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: 当我循环通过<tr>我得到以下输出:

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? 如何在循环时放入分隔符,因为我必须以csv格式保存它?

Looking for this output: 寻找这个输出:

Test1,Test2
Current,Next

My js code: 我的js代码:

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

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 是一种可以实现这些结果的方法,没有尾随或前面的逗号

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/ 示例: http//jsfiddle.net/howderek/ejxqbyrm/

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): 它的重量比其他答案重一点,但试图按照标准逃避一些文本(或接近CSV的标准):

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. 如果由于某种原因每页有多个表,则可以为每个表重用renderer

The version above does some basic escaping per the CSV format, in that it will handle commas, text newlines, and quotes correctly. 上面的版本按CSV格式执行一些基本的转义,因为它将正确处理逗号,文本换行符和引号。 It doesn't handle uneven row lengths, though, and it might be useful to make it convert <br> tags into newlines. 它不处理不均匀排的长度,虽然,这可能会使其转化有用<br>标签成新行。 But for the use cases you've mentioned here, it ought to get the job done. 但是对于你在这里提到的用例,它应该完成工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM