How to Remove last Comma?

Viewed 63766

This code generates a comma separated string to provide a list of ids to the query string of another page, but there is an extra comma at the end of the string. How can I remove or avoid that extra comma?

<script type="text/javascript">
    $(document).ready(function() {
        $('td.title_listing :checkbox').change(function() {
            $('#cbSelectAll').attr('checked', false);
        });
    });
    function CotactSelected() {
        var n = $("td.title_listing input:checked");
        alert(n.length);
        var s = "";
        n.each(function() {
            s += $(this).val() + ",";
        });
        window.location = "/D_ContactSeller.aspx?property=" + s;
        alert(s);
    }
</script>
12 Answers

Use Array.join

var s = "";
n.each(function() {
    s += $(this).val() + ",";
});

becomes:

var a = [];
n.each(function() {
    a.push($(this).val());
});
var s = a.join(', ');
s = s.substring(0, s.length - 1);

You can use the String.prototype.slice method with a negative endSlice argument:

n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"

Or you can use the $.map method to build your comma separated string:

var s = n.map(function(){
  return $(this).val();
}).get().join();

alert(s);

Instead of removing it, you can simply skip adding it in the first place:

var s = '';
n.each(function() {
   s += (s.length > 0 ? ',' : '') + $(this).val();
});

Using 'normal' javascript:

var truncated = s.substring(0, s.length - 1);

A more primitive way is to change the each loop into a for loop

for(var x = 0; x < n.length; x++ ) {
  if(x < n.length - 1)
    s += $(n[x]).val() + ",";
  else
    s += $(n[x]).val();
}

Sam's answer is the best so far, but I think map would be a better choice than each in this case. You're transforming a list of elements into a list of their values, and that's exactly the sort of thing map is designed for.

var list = $("td.title_listing input:checked")
    .map(function() { return $(this).val(); })
    .get().join(', ');

Edit: Whoops, I missed that CMS beat me to the use of map, he just hid it under a slice suggestion that I skipped over.

Here is a simple method:

    var str = '1,2,3,4,5,6,';
    strclean = str+'#';
    strclean = $.trim(strclean.replace(/,#/g, ''));
    strclean = $.trim(str.replace(/#/g, ''));

Related