我有一个JS对象(名为df),它包含许多数组,如下所示:
0: Array(2)
0: "1405"
1: "text string 1 #something"
1: Array(2)
0: "1366"
1: "text string 2 #hashtag"
603: Array(2)
0: "92"
1: "text string 603"
字符串
我想将其导出到csv文件中,如下所示:
| 查看|标题|
| --|--|
| 1405 |文本字符串1 #something|
| 1366 |文本字符串2 #hashtag|
| 92 |文本串603|
我可以使用以下内容导出为csv:
const blob = new Blob([df], { type: "text/csv; charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "export.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
型
但是输出结果很混乱:
| 一|B| C|
| --|--|--|
| 1405 |文本字符串1||
| #某事|||
| | 文本字符串2 #hasthag| text string 2 #hasthag |
我该如何在JS中清理此问题?
编辑:我已经找到了问题的原因是文本字段中的换行符导致剩余文本被推到新的一行。
解决方案是使用regex删除提取文本时的换行符:
innerText.replace(/(\r\n|\n|\r)/gm, " ")
型
1条答案
按热度按时间eagi6jfj1#
只需将对象转换为
CSV
字符串即可字符串
demo
的数据
现场演示
https://codepen.io/xgqfrms/pen/xxmodaB
更新
修复字符串包含
,
符号问题型
的
参考文献
https://en.wikipedia.org/wiki/Comma-separated_values的