我正在使用this code将表格保存为CSV(我已将其更改为包含标题并排除隐藏行)。表格单元格内的某处换行符会丢失,但我想将其保留为\ r \ n。网上有很多类似的问题,但我仍然觉得jQuery有点神秘,不知何故我无法找到解决这个希望简单的问题的方法。如何用 r n替换所有<br />使用jQuery
function exportTableToCSV($table, delimiter) {
var $rows = $table.find('tr:visible');
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
var tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '"' + delimiter + '"',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
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) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
return csvData;
}
的jQuery没有任何字符串处理函数这样的。你应该使用普通的Javascript String.prototype.replace()方法。 – Barmar 2014-11-08 19:57:50
顺便说一句,'text.replace('''''''')只会替换第一个引号,而不是所有的引号。您必须使用带'g'修饰符的正则表达式来执行多个替换。 – Barmar 2014-11-08 19:58:50
谢谢,我已经改正了。 – 2014-11-10 03:16:45