如何删除最后一个逗号?

San*_*nju 31 javascript jquery

此代码生成一个逗号分隔的字符串,以便为另一个页面的查询字符串提供id列表,但字符串末尾有一个额外的逗号.如何删除或避免使用额外的逗号?

<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>
Run Code Online (Sandbox Code Playgroud)

Sam*_*shi 91

使用 Array.join

var s = "";
n.each(function() {
    s += $(this).val() + ",";
});
Run Code Online (Sandbox Code Playgroud)

变为:

var a = [];
n.each(function() {
    a.push($(this).val());
});
var s = a.join(', ');
Run Code Online (Sandbox Code Playgroud)

  • +1 ...比所有这些子串f F更好的方式. (7认同)

Ama*_*osh 27

s = s.substring(0, s.length - 1);
Run Code Online (Sandbox Code Playgroud)

  • 不,它不是*****因为它不验证字符串中的最后一个字符*实际上是*是一个"逗号". (7认同)

CMS*_*CMS 13

您可以使用String.prototype.slice带负endSlice参数的方法:

n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"
Run Code Online (Sandbox Code Playgroud)

或者您可以使用该$.map方法构建逗号分隔的字符串:

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

alert(s);
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 6

您可以直接跳过添加它,而不是删除它:

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


Sen*_*der 5

运用 substring

var strNumber = "3623,3635,";

document.write(strNumber.substring(0, strNumber.length - 1));
Run Code Online (Sandbox Code Playgroud)

运用 slice

document.write("3623,3635,".slice(0, -1));
Run Code Online (Sandbox Code Playgroud)

运用 map

var strNumber = "3623,3635,";

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

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

使用 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(', '));
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)