Stuck extracting data using regular expressions (Javascript)

Status
Not open for further replies.

stodge

Ars Tribunus Militum
1,907
I'm trying to decode some data in Javascript and I thought regular expressions might help. The data is a string like so:

Code:
var data = "['0000', 36],['0005', 36],['0010', 12],['0015', 12]";

It's actually quite a bit longer but this will do for now.

So far I have:

Code:
re = new RegExp("'[0-9]{4}'.{2}[0-9]{2}", "g");
var item = s.match(re);

Which leaves me with an array of strings:

Code:
var arr = ["'0000', 36", "'0005', 36", "'0010', 12","'0015', 12"];

I'm trying to avoid using a loop to then split(",") each array item. So is there a better way of doing this using regular expressions (or something different)? Obviously my regular expression knowledge is very limited. :)

Thanks
 

Catfish

Ars Tribunus Angusticlavius
9,954
You're presumably aware of the quote going something like...
Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.
?


Do you trust your data? If so, you could use eval to turn it into a regular javascript object:
Code:
var dataString = "['0000', 36],['0005', 36],['0010', 12],['0015', 12]";
var data = eval('[' + dataString + ']');
alert(data[0][1]) // 36

However, if a malicious user is able to enter that data, he could just insert arbitrary js and you've got a big security hole. To get around that, you could perhaps massage the data into valid JSON, then parse that.
 
Status
Not open for further replies.