How to convert a Javascript string to an array?

This entire list is provided as a single String variable.

    instruments = '["guitar","bass","drums","keyboard"]';

How to convert String to an array so that I can print each element in its own separate div tag?

    for(var i=0;i<instruments.length;i++){
        document.write("<div>"+instruments[i]+"</div>");
        }
+3
source share
6 answers

If the string contains a valid JSON array (for example, in your example), you can use JSON.parse, for example:

instrumentsString = '["guitar","bass","drums","keyboard"]';
instrumentsArray = JSON.parse(instrumentsString);

Please note that in all browsers there is no function JSON.parse, so you may need to enable the implementation. For example, jQuery comes with one, and you can also use Douglas Crockfords json2.

+4
source

In this case, you can really use the JSON parser :

JSON.parse('["guitar","bass","drums","keyboard"]');
// -> ["guitar", "bass", "drums", "keyboard"]
+3
source

instruments:

JSON.parse() :

var instrumentsArray = JSON.parse(instruments);

, - :

instruments = instruments.replace(/\[(.*?)\]/, "$1");
var instrumentsArray = instruments.split(/,/);

for :

for (var i = 0; i < instrumentsArray.length; i++) {
    // instrumentsArray[i] is the current element
}
+1

if the list of strings has any separator then just use the split function.

Example:

var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
0
source

You can evaluate it to get an array.

var instruments = '["guitar","bass","drums","keyboard"]';
var instruments_array = eval(instruments);
0
source

you can just do evalon it

instruments = '["guitar","bass","drums","keyboard"]';
var instrumentsArray = eval(instruments);

then

for(var i=0;i<instrumentsArray.length;i++){
    document.write("<div>"+instrumentsArray[i]+"</div>");
    }
0
source

Source: https://habr.com/ru/post/1784679/


All Articles