简体   繁体   中英

Separate comma of a string but not included within brackets and parenthesis

I have a elements that has a attribute name of data-options , every element has different configurations , it is not a json formatted for readability and easy maintenance.

<table scoa-table data-options="
responsive:true,
setHeaders:['header1','header2','header3'],
colWidth : 300,
data : {
   "data1" : "value1",
   "data2" : "value2",
   "data3" : "value4",
}`
"></table>

I need to parse a string into a comma separated values

So far, I've got the following :

var foo = jQuery("[scoa-table]").attr("data-options"),
    result = foo.split(/,(?![^\[]*\])/gm)

but it works only in brackets not within on parenthesis

This is what I expected

(3) ["responsive:true", 
    "setHeaders:['header1','header2','header3']",
    "colWidth : 300",
    'data : {"data1" : "value1","data2" : "value2","data3" : "value4",}'
   ]

instead of using the comma, try the "\\n" for new line as split argument: for ur input u can use:

> result = foo.split(/\n(?![^\{]*\})/gm)
[ 'responsive:true,',
'setHeaders:[\'header1\',\'header2\',\'header3\'],',
'colWidth : 300,',
'data : {\n   "data1" : "value1",\n   "data2" : "value2",\n   "data3" : "value4",\n}' ]

BTW: u might need to replace \\n too and the last comma in the splitted line like:

> result = foo.split(/\n(?![^\{]*\})/gm).map(function (e) {return  e.replace(/\n|,$/g, "")})

Loop over the object and use JSON.stringify to convert the key and value to a string before pushing it in an array

 var foo = { responsive: true, setHeaders: ['header1', 'header2', 'header3'], colWidth: 300, data: { "data1": "value1", "data2": "value2", "data3": "value4", } } let arr = []; for (let keys in foo) { arr.push(`${keys}:${JSON.stringify(foo[keys])}`) } console.log(arr) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM