I have following string in javascript variable
var days="1,2,3";
now I want this in following way as javascript variable with JSON format like
jdays=["1", "2", "3"];
Is there anyway to do so?
3 Answers 3
This will work
var days = "1,2,3",
jdays = days.split(',');
console.log(jdays); // ["1", "2", "3"]
String.prototype.split() is used to split a string into an array by removing every instance of the string passed to it as a parameter and pushing each fragment of the string to the array.
The array created by String.prototype.split() is the return value of the function.
by using split function you can do this
var daysArr = days.split(',')
Comments
If, when you say you "want this in following way as a javascript variable" you mean you want that JSON format string in a variable.. then..
jsonstring = 'jdays='+JSON.stringify(days.split(','));
3? Trydays.split(',');, ordays.match(/\d+/g)