如何删除属性值中的最后一个逗号?

时间:2015-10-16 12:21:17

标签: jquery html

我想删除data-group属性中的最后一个逗号:

<div data-groups='["all", "food", "tool",]'></div>

我需要这样:

<div data-groups='["all", "food", "tool"]'></div>

如何使用jQuery执行此操作?

2 个答案:

答案 0 :(得分:1)

尝试

$("div").attr("data-groups", $("div").attr("data-groups").slice(0,-2) + "]");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-groups='["all", "food", "tool",]'></div>

或添加课程

$(".group").attr("data-groups", $(".group").attr("data-groups").slice(0,-2) + "]");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group" data-groups='["all", "food", "tool",]'></div>

答案 1 :(得分:0)

$('[data-groups]').each(function() {
    var groups = $(this).data('groups');
    var trimmed = groups.substring(0, groups.length - 2);
   $(this).attr('data-groups', trimmed + ']');
});
div:after {
    content: attr(data-groups);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div data-groups='["all", "food", "tool",]'>Groups </div>

或不太可读......

$('[data-groups]').each(function() {
    var $this = $(this);
    $this.attr('data-groups', $this.data('groups').substring(0, $this.data('groups').length - 2) + ']');
});