views:

21

answers:

1

Hi! I have this ReGex expression in JavaScript right now: /(.*)(,)([\]\}]+)$/.exec(stringData). Basically it's removing any trailing comma from a malformed JSON string, (by concatenating r[1] + r[3] you get it).

It's working well except it's way too slow on big strings. So a regex is not a good choice here. I would like to convert this to a function, could anybody write it? Sorry if this is inappropriate, I feel ashame to ask but I'm in a hurry and my level's very poor in JS.

Plus I think it would be useful for the community, this question was not asked before from what I've seen.

Here are some examples:

cleanJSON('{time:23423,}') --> '{time:23423}'
cleanJSON('{times:[23423,]}') --> '{times:[23423]}'
cleanJSON('{times:[23423,4353], ids:[434,634],}') --> '{times:[23423,4353], ids:[434,634]}'

TIA

A: 

Maybe it would be better to do something like

"thisis,a,very,big,string".replace(/,([]}]+)$/g, "$1");
thejh
It seems much faster. I'll test it more thoroughly.
Mister Small
Yep your optimization works fine.
Mister Small
I combined it with some subselection on the 15 last bytes of the string in order to reduce the computation time even more, although it will be less generic: data = data.substr(0, data.length - 15) + data.substr(-15).replace(/,([]}]+)$/g, "$1"); Thank you very much :)
Mister Small