Reputation: 1071
I am using the following function to export a table to a csv file for our users to export a copy of their purchases to a format they can use in quickbooks, excel, etc.
The function works great, except that the first column of our table contains urls and these columns appear blank in the export.
I am wondering how i could modify this so when a link is encountered as a field the text of that link would be added to the csv.
Example: <a href="example.php">an example</a>
would add an example
to the csv for that field.
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td),tr:has(th)'),
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
colDelim = '","',
rowDelim = '"\r\n"',
csv = '"' + $rows.map(function (i, row) {
var $row = $(row), $cols = $row.find('td,th');
return $cols.map(function (j, col) {
var $col = $(col), text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim).split(tmpRowDelim).join(rowDelim).split(tmpColDelim).join(colDelim) + '"',
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
console.log(csv);
if (window.navigator.msSaveBlob) { // IE 10+
window.navigator.msSaveOrOpenBlob(new Blob([csv],
{type: "text/plain;charset=utf-8;"}),
"csvname.csv")
} else {
$(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' });
}
}
Upvotes: 0
Views: 656
Reputation: 189
As far as I can see, your snippet should already support this. It iterates over all rows of the table and for each row over all of its column fields, where jQuery's text() function is applied in order to extract the text. This should return the text between a tags as well.
Example:
console.log($('<td><a href="test.html">Test page</a></td>').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
will return the string Test page
.
This fiddle contains the function you provided and a dummy table with some anchor elements. In my opinion it already meets your requirements.
Upvotes: 1
Reputation: 25
var a = document.createElement('a');
a.href = "http://example.php";
a.append("an example");
document.body.appendChild(a);
console.log(a.textContent);
Upvotes: 0