Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Jquery Convert string to array

Tags:

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?

like image 671
maaz Avatar asked Aug 02 '12 11:08

maaz


People also ask

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you iterate in jQuery?

. each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.


1 Answers

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 
like image 180
Joseph Avatar answered Oct 24 '22 13:10

Joseph