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?
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.
. 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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With