Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the second last character of a string

Tags:

javascript

How would I remove the second last character of a string using pure javascript. I can make it more specific by saying the last character of the string is ','. But there are other ',' present in the string. I just want the 2nd last one to be gone

here is the string

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"
}, ]

Notice the last ','

the script which is producing it is this

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 += ']';
like image 934
soum Avatar asked Jan 27 '14 21:01

soum


1 Answers

This will truncate the last two characters of the string (and add a ] back on):

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

jsFiddle example

like image 134
j08691 Avatar answered Oct 04 '22 20:10

j08691