user2571510
user2571510

Reputation: 11377

Avoid comma at end of .each loop in jQuery

I am using the following lines to create a list of values separated with a comma and a space.

How can I set this so that the comma and space only appear between the single values but not at the end of the string ?

var headers = '';
$('#myTable').find('.myHeader').each(function() {
    headers += "'" + $(this).text() + "', ";
});
alert(headers);

Upvotes: 0

Views: 82

Answers (4)

Mottie
Mottie

Reputation: 86413

Alternatively you can use an array (demo)

var headers = [];
$('#myTable').find('.myHeader').each(function () {
    headers.push( "'" + $(this).text() + "'" );
});
alert(headers.join(', '));

Upvotes: 0

dafi
dafi

Reputation: 3522

You must use the index

var headers = '';
var sel = $('#myTable').find('.myHeader');
selCount = sel.length - 1;
sel.each(function(index) {
    headers += "'" + $(this).text() + "'";
    console.log(index)
    if (selCount != index) {
        headers += ", ";
    }
});
alert(headers);

Upvotes: 0

Try

str.substring(indexA, indexB)

headers = headers.substring(0, headers.length - 2);//extract substring ignoring last two characters

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68400

This could do the trick

var headers = '';
var separator = '';
$('#myTable').find('.myHeader').each(function() {
    headers += separator + "'" + $(this).text() + "'";
    separator = ',';
});

Upvotes: 1

Related Questions