我是javascript的新手,我有一个长字符串,我希望在第三个逗号之后拆分并更改不同格式。如果你不了解我的问题。请参阅以下示例
我的字符串:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
我想要这样的输出:(每个项目应该在下一行)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
如何使用JavaScript更改这样的内容?
答案 0 :(得分:1)
只需复制并粘贴即可。功能更加动态。
示例数据
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
<强>功能强>
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
<强>用法强>
writeData(testData);
答案 1 :(得分:0)
使用split
方法转换数组中的字符串,并从lodash或下划线转换chunk
以将数组分成3个部分。
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
答案 2 :(得分:0)
您可以使用split
在每个逗号上拆分字符串。下一步是迭代元素,将当前元素放入缓冲区,并在缓冲区大小为3时刷新缓冲区。所以它就像:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
答案 3 :(得分:0)
如果您已修复此字符串,则可以使用它,否则验证字符串。
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);