Nishant123 Nishant123 - 5 months ago 7
Javascript Question

Regex for creating an array from String

I have a string as follows

var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";


I want to get three arrays from above string as follows

var arr1 = ["series-3","series-5","series-6"];

var arr2 = ["a3","a4","a5"];

var arr3 = ["class a", "class b"];


What regex should I use to achieve this?
Can this be done without regex?

Answer

Use String#split() method

var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";

// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);

// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');

console.log(arr1, arr2, arr3);


Or same method with some variation

var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";

// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');

// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');

console.log(arr1, arr2, arr3);

Comments