Sanju
Sanju

Reputation: 903

How to Remove last Comma?

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>

Upvotes: 32

Views: 66690

Answers (13)

Abijith Ajayan
Abijith Ajayan

Reputation: 274

Simple Answer

var string = "apple,orange,strawberry";
var totalstringcount = string.split(",").length;
console.log("Before removing comma - "totalstringcount);

var laststring = string.replace(/,\s*$/, "");
var totalstringcount2 = laststring.split(",").length;
console.log("After removing comma - "totalstringcount2);

Upvotes: 0

Kaya M
Kaya M

Reputation: 11

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

Upvotes: 0

Sender
Sender

Reputation: 6858

Using substring

var strNumber = "3623,3635,";

document.write(strNumber.substring(0, strNumber.length - 1));

Using slice

document.write("3623,3635,".slice(0, -1));

Using map

var strNumber = "3623,3635,";

var arrData = strNumber.split(',');

document.write($.map(arrData, function(value, i) {
  return value != "" ? value : null;
}).join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Use Array.join

var strNumber = "3623,3635,";
var arrTemp = strNumber.split(',');
var arrData = [];

$.each(arrTemp, function(key, value) {
  //document.writeln(value);
  if (value != "")
    arrData.push(value);
});

document.write(arrData.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 5

Vikas Kottari
Vikas Kottari

Reputation: 495

you can use below extension method:

String.prototype.trimEnd = function (c) {
    c = c ? c : ' ';
    var i = this.length - 1;
    for (; i >= 0 && this.charAt(i) == c; i--);
    return this.substring(0, i + 1);
}

So that you can use it like :

var str="hello,";
str.trimEnd(',');

Output: hello.

for more extension methods, check below link: Javascript helper methods

Upvotes: 0

miku
miku

Reputation: 188234

Using 'normal' javascript:

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

Upvotes: 3

Md Nazmoon Noor
Md Nazmoon Noor

Reputation: 3317

Write a javascript function :

var removeLastChar = function(value, char){
    var lastChar = value.slice(-1);
    if(lastChar == char) {
      value = value.slice(0, -1);
    }
    return value;
}

Use it like this:

var nums = '1,2,3,4,5,6,';
var result = removeLastChar(nums, ',');
console.log(result);

jsfiddle demo

Upvotes: 0

duyn9uyen
duyn9uyen

Reputation: 10331

 s = s.TrimEnd(",".ToCharArray());

Upvotes: -1

Joel Mueller
Joel Mueller

Reputation: 28764

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.

Upvotes: 1

Sam Doshi
Sam Doshi

Reputation: 4376

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(', ');

Upvotes: 93

o.k.w
o.k.w

Reputation: 25830

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

Upvotes: 2

Guffa
Guffa

Reputation: 700910

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

Upvotes: 7

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828200

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

Upvotes: 13

Amarghosh
Amarghosh

Reputation: 59471

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

Upvotes: 27

Related Questions