I want to convert the following string to an array
var string = '["YES","NO"]';
How do I do this?
asked Jun 12, 2015 at 5:53
Sriya
1872 gold badges3 silver badges10 bronze badges
-
is array object == array of objectsRoli Agrawal– Roli Agrawal2015年06月12日 05:55:54 +00:00Commented Jun 12, 2015 at 5:55
-
Convert string to array? This is already array. Describe your problem in details and tell us what you triedMaciej Baranowski– Maciej Baranowski2015年06月12日 05:56:01 +00:00Commented Jun 12, 2015 at 5:56
-
1This is not a array. This is string. This is what i got first into my javascript Object {1: "["YES","NO"]"} And now i want to convert this keys value("["YES","NO"]") into arraySriya– Sriya2015年06月12日 05:58:35 +00:00Commented Jun 12, 2015 at 5:58
3 Answers 3
use the global JSON.parse method
JSON.parse('["YES","NO"]'); // returns ["YES", "NO"]
You can also use the JSON.stringify method to write the array back to a string if thats how you are storing it.
JSON.stringify(["YES", "NO"]); // returns '["YES", "NO"]'
answered Jun 12, 2015 at 6:03
t3dodson
4,0273 gold badges31 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Michael Geary
And the improved readability is the least important thing about it.
var str= '["YES","NO"]';
var replace= str.replace(/[\[\]]/g,'');
var array = replace.split(',');
Fiddle : http://jsfiddle.net/9amstq41/
answered Jun 12, 2015 at 5:59
Thibault Bach
5565 silver badges8 bronze badges
3 Comments
Michael Geary
alert( "YES".length ); alert( array[0].length );Michael Geary
var str= '["Are you [[sure?]]","No, not really"]';Omar Dulaimi
I would add a
.filter(Boolean) after the split to remove empty string values.You can also use $.parseJSON:
var string = '["YES","NO"]';
var array = $.parseJSON(string);
Comments
lang-js