Home > Software engineering >  Split a string by comma in excluding braces
Split a string by comma in excluding braces

Time:03-27

I am very much new to regex and I have a requirement to split a string by comma and generate a array out of it. Any pointer will be really helpful.

In my result array should have 3 item and all nested comma inside {} and () need to be ignored split should be done only on outer comma. Refer the output image

I have tried below regex in javascript but it is not solving problem completly

,(?!\[^{\[('\]\*\[}\])'\])/g

Actual string

let mystr =`attrs :{id:'hello'},ojComponent: {component:'Button', display: 'icons', chroming: 'half', icons: {start:'cartWedgitIcon', end: null}, label: $module.cartBtnLabel}, visible:('true',condition)`;
let arrayofItem = mystr.split(\<\<Regex\>\>);

**Expected output **

CodePudding user response:

For such kind of reuirement regex is not the ideal solution , so I have written my own parser to handle this usecase. Which will process entire string charter by character.

CodePudding user response:

I suggest you trying to get firstly pure words out of context by implementing regular expression. Then, because in JSON every word including keys and values demand to be wrapped by single or double quotes, you may add it after getting each word inside an array function. You should use array methods to work on each word. Code sample I may suggest to use is below.

const regX = /[a-zA-Z] /; let matched = yourString.match(regX);

P.S. Don't forget to retain true and false words out of context as they aren't wrapped inside quotes.

  • Related