26

i have a string

var traingIds = "${triningIdArray}";  // ${triningIdArray} this value getting from server 
alert(traingIds)  // alerts [1,2]
var type = typeof(traingIds ) 
alert(type)   // // alerts String

now i want to convert this to array so that i can iterate

i tried

var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) { 
    alert(index + ': ' + value);   // alerts 0:[1 ,  and  1:2]
});

how to resolve this?

maaz
  • 3,534
  • 19
  • 61
  • 100

5 Answers5

76

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]

//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Wow, this is just brilliant... and simple Thank you. – Watercayman Feb 19 '20 at 23:57
  • 3
    I have input just like OPs, except the var is set to the .attr() of my element. It has `typeof string` and looks like `"['foo','bar']"`. When I try JSON.parse i get the `Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse ()` error. Any idea? – KuboMD Jun 05 '20 at 21:03
14

Change

var trainindIdArray = traingIds.split(',');

to

var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61
11

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

var traingIds = ${triningIdArray};

not

var traingIds = "${triningIdArray}";
Mitya
  • 33,629
  • 9
  • 60
  • 107
5

check this out :)

var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
alert(traingIds);  // alerts [1,2]
var type = typeof(traingIds);
alert(type);   // // alerts String

//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds);  // alerts 1,2        
var trainindIdArray = traingIds.split(',');

​for(i = 0; i< trainindIdArray.length; i++){
    alert(trainindIdArray[i]); //outputs individual numbers in array
    }​ 
Clayton
  • 457
  • 2
  • 8
  • 2
    You can use eval. eg. eval("[1,2]") # => [1,2] – Sam Kah Chiin Dec 19 '16 at 06:50
  • It surprises me @Sam Kah Chiin 's comment is not an answer. It really a great deal to this question. it is single lined and simple. Thanks – Young Emil Feb 04 '18 at 12:37
  • 2
    @YoungMillie, actually using `eval` in javascript can be dangerous as improper use of eval opens up your code for injection attacks. Check this [stackoverflow](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) :) – Sam Kah Chiin Feb 06 '18 at 07:34
  • Thanks @Sam Kah Chiin , knowledge is power. I now understand what eval is and how dangerous it can be. – Young Emil Feb 06 '18 at 08:20
  • Then in that case...I guess @Clayton 's answer is also a good way around the problem. – Young Emil Feb 06 '18 at 08:27
0

There are four ways to convert a string into an array in JavaScript. Here you have code examples on how they look.

Example Code:

let string = "Javascript";

First Method:

let array = [string];

Second Method:

let array = [...string];

Third Method:

let array = Array.from(string); 

Fourth Method:

let array = string.split('');

I hope that my answer helps you!

AztecCodes
  • 1,130
  • 7
  • 23