user2593318
user2593318

Reputation: 35

remove quotes before an array list using jquery

I have been strugling with a problem, I am using

var srlisthidden = $('#hiddenroutList').val();

srlisthidden returns an array of list but in quotes "['0015','0016']"

$.each(srlisthidden, function(i, value) {
});

But because of the double quotes on the beginning of the array,it is not allowing the list to iterate even, I tried many different options to remove the double quotes like regEx and

jQuery.parseJSON('['+srlisthidden+']'), but none of them worked, Please give me solution.

Upvotes: 0

Views: 1776

Answers (3)

nbrooks
nbrooks

Reputation: 18233

JSON requires inner quotes around strings be double-quotes escaped with a backslash; the parser doesn't play nicely with single quotes.

Clean up your string with regex:

var str = srlisthidden.replace(/\'/g, "\"")

Output: ["0015","0016"] (as a string)

Then parse as JSON:

JSON.parse(str)

Output: ["0015", "0016"] (as an array)

Upvotes: 0

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

You can achieve it like this as well

var to_parse =  "['0015','0016']"; 
var array = parse.replace(/\[|]|'/g, '').split(',');

Upvotes: 0

Louis93
Louis93

Reputation: 3923

Try this out:

var x =  "['0015','0016']"; // The value that you are grabbing
var sol = eval(x); // This returns the value as an array of strings.

Is this what you are trying to achieve?

Upvotes: 2

Related Questions