Saiprakash Holi Saiprakash Holi - 5 months ago 23
Javascript Question

convert String to array in javascript "datastatusMonthly[0]"

datastatusMonthly[0]
- This is my String in javascript
If i print this, it is printing as same string.

How do i get the value of '0' index in array
datastatusMonthly
using this above string?

Any help please?

Answer Source

Solution without eval, which is evil, using regex with group:

var datastatusMonthly = [3];

var text = 'datastatusMonthly[0]';
var regex = /(datastatusMonthly)\[([0-9]+)\]/g;
var match = regex.exec(text);

var arrayName = match[1];
var arrayIndex = match[2];

console.log(window[arrayName][arrayIndex]);