Question

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);
Was it helpful?

Solution

Try

str.substring(indexA, indexB)

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

OTHER TIPS

This could do the trick

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

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);

Alternatively you can use an array (demo)

var headers = [];
$('#myTable').find('.myHeader').each(function () {
    headers.push( "'" + $(this).text() + "'" );
});
alert(headers.join(', '));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top