删除字符串的倒数第二个字符

时间:2014-01-27 21:08:28

标签: javascript

如何使用纯javascript删除字符串的倒数第二个字符。我可以通过说字符串的最后一个字符是','来使它更具体。但是字符串中还有其他','。我只想让第二个最后一个消失

这是字符串

var data = [{
  "Store_ID": "46305",
  "inv list id": "jonesny-46305-inventory",
  "Store Address": "739 Reading Avenue Suite #306",
  "zip": "19610"
}, {
  "Store_ID": "48760",
  "inv list id": "jonesny-46305-inventory",
  "Store Address": "1665 State Hill Rd",
  "zip": "19610"
}, {
  "Store_ID": "48811",
  "inv list id": "jonesny-46305-inventory",
  "Store Address": "1665 State Hill Road",
  "zip": "19601"
}, {
  "Store_ID": "53046",
  "inv list id": "jonesny-46305-inventory",
  "Store Address": "2630 Westview Dr",
  "zip": "19610"
}, ]

注意最后一个','

生成它的脚本就是这个

var newVar = '[';

for(var x in pdict.Stores){
    newVar += '{' + '"Store_ID":"' + x.ID + '",';
    newVar += '"inv list id":"' + x.inventoryList.ID + '",';
    newVar += '"Store Address":"' + x.address1 + '",';
    newVar += '"zip":"' + x.postalCode + '"},';
}

newVar += ']';

1 个答案:

答案 0 :(得分:5)

这将截断字符串的最后两个字符(并重新添加]):

str = str.substring(0, str.length - 2)+ ']';

<强> jsFiddle example