我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)
当前回答
Papa Parse处理值中的逗号和其他边缘情况。
(Baby Parse for Node已弃用-你现在可以在浏览器和Node中使用Papa Parse。)
如。(节点)
const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;
1,,“a,b”
其他回答
从Chrome 72开始,可以使用Intl。ListFormat:
const vehicles = ['Motorcycle', 'Bus', 'Car']; const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); console.log(formatter.format(vehicles)); // expected output: "Motorcycle, Bus, and Car" const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' }); console.log(formatter2.format(vehicles)); // expected output: "Motorcycle, Bus oder Car" const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' }); console.log(formatter3.format(vehicles)); // expected output: "Motorcycle Bus Car"
请注意,这种方法还处于非常早期的阶段,所以在发布这个答案的日期,预计与旧版本的Chrome和其他浏览器不兼容。
我认为这应该做到:
var arr = ['contains,comma', 3.14, 'contains"quote', "more'quotes"]
var item, i;
var line = [];
for (i = 0; i < arr.length; ++i) {
item = arr[i];
if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('"') !== -1)) {
item = '"' + item.replace(/"/g, '""') + '"';
}
line.push(item);
}
document.getElementById('out').innerHTML = line.join(',');
小提琴
基本上,它所做的就是检查字符串是否包含逗号或引号。如果是,那么它将所有的引号都翻倍,并在结尾加上引号。然后用逗号将每个部分连接起来。
你想以"and"结尾吗?
对于这种情况,我创建了一个npm模块。
试试arrford:
使用
const arrford = require('arrford');
arrford(['run', 'climb', 'jump!']);
//=> 'run, climb, and jump!'
arrford(['run', 'climb', 'jump!'], false);
//=> 'run, climb and jump!'
arrford(['run', 'climb!']);
//=> 'run and climb!'
arrford(['run!']);
//=> 'run!'
安装
npm install --save arrford
阅读更多
https://github.com/dawsonbotsford/arrford
自己试试吧
主音链接
在这里,您可以使用任何char进行分离,也可以仅使用foreach获取任何属性列表
let taskIds: string = '';
this.checkedTaskList.forEach(res => {
taskIds = taskIds + res.taskId.toString() + ','
});
if (taskIds) {
taskIds.substring(0, taskIds.length - 1),**
}
下面是将二维数组或列数组转换为正确转义的CSV字符串的实现。函数不检查有效的字符串/数字输入或列计数(确保数组从一开始就是有效的)。单元格可以包含逗号和引号!
这里有一个解码CSV字符串的脚本。
这是我编码CSV字符串的脚本:
// Example
var csv = new csvWriter();
csv.del = '\t';
csv.enc = "'";
var nullVar;
var testStr = "The comma (,) pipe (|) single quote (') double quote (\") and tab (\t) are commonly used to tabulate data in plain-text formats.";
var testArr = [
false,
0,
nullVar,
// undefinedVar,
'',
{key:'value'},
];
console.log(csv.escapeCol(testStr));
console.log(csv.arrayToRow(testArr));
console.log(csv.arrayToCSV([testArr, testArr, testArr]));
/**
* Class for creating csv strings
* Handles multiple data types
* Objects are cast to Strings
**/
function csvWriter(del, enc) {
this.del = del || ','; // CSV Delimiter
this.enc = enc || '"'; // CSV Enclosure
// Convert Object to CSV column
this.escapeCol = function (col) {
if(isNaN(col)) {
// is not boolean or numeric
if (!col) {
// is null or undefined
col = '';
} else {
// is string or object
col = String(col);
if (col.length > 0) {
// use regex to test for del, enc, \r or \n
// if(new RegExp( '[' + this.del + this.enc + '\r\n]' ).test(col)) {
// escape inline enclosure
col = col.split( this.enc ).join( this.enc + this.enc );
// wrap with enclosure
col = this.enc + col + this.enc;
}
}
}
return col;
};
// Convert an Array of columns into an escaped CSV row
this.arrayToRow = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.escapeCol(arr2[i]);
}
return arr2.join(this.del);
};
// Convert a two-dimensional Array into an escaped multi-row CSV
this.arrayToCSV = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.arrayToRow(arr2[i]);
}
return arr2.join("\r\n");
};
}