0

I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example

My string:

var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";

I want output like this:(Each item should be in next line)

Idly(3 Pcs) - 10 = 200

Ghee Podi Idly - 10 = 300

How to change like this using JavaScript?

help-info.de
  • 6,695
  • 16
  • 39
  • 41
hikoo
  • 517
  • 4
  • 10
  • 20

4 Answers4

0

Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 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]);
});
Marcos Kubis
  • 485
  • 1
  • 4
  • 11
0

You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:

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 = [];
  } 

}

mm759
  • 1,404
  • 1
  • 9
  • 7
0

If you have fix this string you can use it otherwise validate string.

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);
Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
0

Just copy and paste it. Function is more dynamic.

Example Data

var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";

Function

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;
}

Usage

writeData(testData);
Fatih TAN
  • 778
  • 1
  • 5
  • 23