Reputation: 614
I have the below code that is trying (unsuccessfully) to remove the last comma from the outputted string below.
jQuery(function($){
var string = "{image : 'melbourne.jpg'},{image : 'tunnel.jpg'},{image : 'building.jpg'},";
$.supersized({
slide_interval : 3000,
slides : [ string.substring(0, string.length - 1) ]
});
});
But what I need is this:
jQuery(function($){
var string = "{image : 'melbourne.jpg'},{image : 'tunnel.jpg'},{image : 'building.jpg'},";
$.supersized({
slide_interval : 3000,
slides : [ {image : 'melbourne.jpg'},{image : 'tunnel.jpg'},{image : 'building.jpg'} ]
});
});
I've tried a heap of different things, but to no avail. I'm not sure what I am doing wrong!!
Upvotes: 0
Views: 1059
Reputation: 417
You need to process your data first:
var imageStr = "{image : 'melbourne.jpg'},{image :'tunnel.jpg'},{image :'building.jpg'},";
imageStr = imageStr.substring(0, imageStr.length - 1)
imagesArray = imageStr.split(',');
var jsonObj;
var imageList = [];
for(var i = 0; i < imagesArray.length; i++){
jsonObj = eval("("+imagesArray[i]+")");
imageList.push(jsonObj);
}
var data = JSON.stringify(imageList);
After processing, you may then use the data variable as such:
slider: data
Upvotes: 0
Reputation: 160833
Don't pass data like that using string, using javascript objects.
jQuery(function($){
var slides = [{image : 'melbourne.jpg'},
{image : 'tunnel.jpg'},
{image : 'building.jpg'}];
$.supersized({
slide_interval : 3000,
slides : slides
});
});
You may say that string comes from the server side, then you should fix the data in the server side let it could be parse to be an javascript object.
But if you do not listen to my advise and stick to that string, you may touch the eval
evil.
jQuery(function($){
var string = "{image : 'melbourne.jpg'},{image : 'tunnel.jpg'},{image : 'building.jpg'},";
$.supersized({
slide_interval : 3000,
slides : eval("["+string.substring(0, string.length - 1)+"]")
});
});
Upvotes: 0
Reputation: 26281
You are correct about your str.substring(0, str.length - 1);
But you didn't create your string object var string = '{image : 'melbourne.jpg'},{image : 'tunnel.jpg'},{image : 'building.jpg'},';
correctly. First, you don't want quotes around it. Secondly, it is malformed. Thirdly, listen to elclanrs!
Upvotes: 1