D. Rattansingh D. Rattansingh - 1 year ago 49
Javascript Question

Splitting a string between two reoccurring characters

I have dynamic values in a variables, each separated with [ and ] e.g.

var data="[Continuing] [Returning] "; or
var data="[ACCT_BBA] "; or
var data="[12001] [12009] [21077] [13880] ";
var data="[13880] ";

Is there a way to use the split function to extract the values between the [ and the ] from above?

var arr= data.split("<what goes here?>");

e.g. on the last example to retrieve: 12001, 12009, 21077, 13880

Answer Source
data.slice(1, -2).split("] [")

should do the job, or if your start and end are uncertain maybe

data.replace(/^\s*\[|\]\s*$/g, "").split("] [")

Alternatively, if you need something more complex, the choice is usually .match with a global regex, or building your own parser if you need to handle arbitrarily nested structures.