所以我试图加入一个数组,所以我可以将字符串保存为csv。 它工作但我得到额外的报价和列显示在csv文件中,我如何解决我的问题。
var arr = ["Merry, Christmas", "Halloween", "New Years", "other"]
var quotedAndCommaSeparated = "'" + arr.join("','") + "'";
将字符串保存到csv文件后,有2个问题。
有两个双引号,一个在csv的行的开头和结尾。 数组中的第一个字符串也被分成2列,因为它有一个逗号。
答案 0 :(得分:0)
CSV
文件格式不适用于单引号(')
,您可以更改您的连接字符串,如下所示。
var arr = ["Merry, Christmas", "Halloween", "New Years", "other"]
var quotedAndCommaSeparated = '"' + arr.join('","') + '"';
console.log(quotedAndCommaSeparated);
答案 1 :(得分:0)
根据spec for a CSV,您必须使用:
var arr = ["Merry, Christmas", "Halloween", "New Years", "Item with \"Double Quoted\" string"];
// Temporary array to store the modified entries in for the CSV
var arrDoubled = [];
// Loop over the original array, and double up the double quotes
// by taking each item in the `arr` array, and doing a global (`g`) replace
// to change all " to ""
arr.forEach(function(item) {
arrDoubled.push(item.replace(/"/g, '""'));
});
// Use Double Quotes instead of single for the CSV
// Note that '"' is the same as "\"" (each is a string with a single double quote as contents)
var quotedAndCommaSeparated = "\"" + arrDoubled.join("\",\"") + "\"";
console.log(quotedAndCommaSeparated);