Home > Mobile >  JavaScript Split string and create new arrays
JavaScript Split string and create new arrays

Time:11-09

I have below string

"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~

I need to split by ~ and should create separate arrays with double quotes "". Below is expected

[
    ["ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"],
    ["100000000","1000048","0010041","1","1","1","1"],
    ["100000000","1000048","0010041","1","1","1","1"],
    ["100000000","1000048","0010041","1","1","1","1"],
]   

This is what i have tried.

str.split('~').slice(2)

Which does not split to separate arrays. How to achieve the same. Thanks in Advance

CodePudding user response:

You can first split with ~ and then split each sub array with ,. The code below is also removing the empty strings "". IF you want them included just remove the .filter(i => i)

EDIT: removed the empty strings filter

const s = '"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~'

const arr1 = s.split('~')

const arr2 = arr1.map(arr => {
  arr = arr.replace(/\"/g, '')
  return arr.split(',')
})

console.log(JSON.stringify(arr2, null, 2))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related