Reputation: 11377
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
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
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
Reputation: 57105
Try
headers = headers.substring(0, headers.length - 2);//extract substring ignoring last two characters
Upvotes: 1
Reputation: 68400
This could do the trick
var headers = '';
var separator = '';
$('#myTable').find('.myHeader').each(function() {
headers += separator + "'" + $(this).text() + "'";
separator = ',';
});
Upvotes: 1