Forum Moderators: open

Message Too Old, No Replies

Removing the last instance from a loop with jQuery

Removing the last instance from a loop with jQuery

         

whyyi

1:26 am on May 13, 2011 (gmt 0)

10+ Year Member



Bit of a newbie here so bear with me:

So I'm looping through entries in a database and the output for each one looks similar to this:

{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},



The problem is that I need to remove the last character (the comma) from the last instance in the loop.
It would be preferred if I did this with jquery but I'm not much of a programmer and have no clue how
to do this.

Thanks for the help!

Fotiman

2:24 am on May 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



What is the output? Is it a string? You can do this without jQuery. You just need the JavaScript string.substr or string.substring method. For example:

var myString = "foot";
myString = myString.substr(0, myString.length - 1);
alert(myString); // "foo"

whyyi

5:31 pm on May 13, 2011 (gmt 0)

10+ Year Member



Thanks for replying Fotiman :)

It's actually just a comma. But how would you do this for the last instance of something so:

{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},


Is looping through so there's a lot of instances for.

{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},

{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},

{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},



So how would I remove the comma in the last instance of "},"

Thanks so much!

Fotiman

5:55 pm on May 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm not sure what this is that you're posting? Is this getting put into a variable in JavaScript? If so, then the example I posted above will work... it will strip off the last character, regardless of what character it is.

whyyi

8:04 pm on May 13, 2011 (gmt 0)

10+ Year Member



Sorry I should have been more clear it's in a ruby each do loop like below:

<script type ="text/javascript">
$(document).ready(function() {

<%- @test.name.each do |user| -%>
{
title: 'test',
description: 'test',
url: 'http://www.test.com'
},

});
</script>

And it will output various instances of the loop and I'm trying to remove in the last instance of the loop the last comma but not remove it from the other ones.

Fotiman

8:49 pm on May 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm not really familiar with Ruby syntax, however, I believe you need to search within Ruby for your solution. For example, perhaps you get the last item in the collection and handle it differently.