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?
5 Answers 5
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
2 Comments
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 (<anonymous>) error. Any idea?Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
Comments
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}";
Comments
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
}
5 Comments
eval in javascript can be dangerous as improper use of eval opens up your code for injection attacks. Check this stackoverflow :)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!