Trim the last character at the end of string Trim the last character at the end of string json json

Trim the last character at the end of string


Have found the simplest way over the years is to let the loop generate the extra character than just trim it after the execution of the loop using Left().

After your loop add;

items = Left(items, Len(items) - 1)

This way avoids having to add a load of logic into the loop to handle the edge cases unnecessarily.


Move your comma to the beginning of the loop and put it in a conditional statement so that it isn't executed at the first iteration

do until rsheadercart.eof     If items <> "" then        items = items & ","    End If         items = items & " { sku: '" & rsheadercart("ten_digit_part_number") & "',"    items = items & " display_name:'" & rsheadercart("part_name") & "',"    items = items & " unit_price: " & rsheadercart("price") & ","    items = items & " qty: " & rsheadercart("quantity") & " } "rsheadercart.movenextloop 


In cases like that I often use the Join method

dim itemList set itemList = CreateObject("System.Collections.ArrayList")do until rsheadercart.eof     dim item           item = " { sku: '" & rsheadercart("ten_digit_part_number") & "',"    item = item & " display_name:'" & rsheadercart("part_name") & "',"    item = item & " unit_price: " & rsheadercart("price") & ","    item = item & " qty: " & rsheadercart("quantity") & " } "    itemList.Add item    rsheadercart.movenextloop items = Join(itemList.ToArray,",")

If you don't want to use an Arraylist, you can do the same with an plain array, but you would have to redim it each iteration.