12

I want to convert the following string to an array

var string = '["YES","NO"]';

How do I do this?

3
  • is array object == array of objects Commented Jun 12, 2015 at 5:55
  • Convert string to array? This is already array. Describe your problem in details and tell us what you tried Commented Jun 12, 2015 at 5:56
  • 1
    This 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 array Commented Jun 12, 2015 at 5:58

3 Answers 3

15

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"]'
Sign up to request clarification or add additional context in comments.

1 Comment

And the improved readability is the least important thing about it.
4
var str= '["YES","NO"]';
var replace= str.replace(/[\[\]]/g,'');
var array = replace.split(',');

Fiddle : http://jsfiddle.net/9amstq41/

3 Comments

alert( "YES".length ); alert( array[0].length );
var str= '["Are you [[sure?]]","No, not really"]';
I would add a .filter(Boolean) after the split to remove empty string values.
0

You can also use $.parseJSON:

var string = '["YES","NO"]';
var array = $.parseJSON(string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.