How to Remove last Comma?

后端 未结 12 1915
自闭症患者
自闭症患者 2020-12-08 06:58

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 re

相关标签:
12条回答
  • 2020-12-08 07:48

    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

    0 讨论(0)
  • 2020-12-08 07:49

    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.

    0 讨论(0)
  • 2020-12-08 07:51

    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();
    }
    
    0 讨论(0)
  • 2020-12-08 07:54

    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

    0 讨论(0)
  • 2020-12-08 07:57

    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();
    });
    
    0 讨论(0)
  • 2020-12-08 07:58

    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);
    
    0 讨论(0)
提交回复
热议问题