Trim the last character at the end of string

Viewed 146

I have a loop that is creating a string until the end of the file. Depending on how many products I have at the time. I need to trim the last comma at the end.

I get:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 },

I need:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 }

Loop:

<%
set rsheadercart = db.execute(sqlheadercart)
    if not rsheadercart.eof then 
        do until rsheadercart.eof 




            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.movenext
        loop 
        %>
<%
end if 
%>
3 Answers

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.movenext
loop 

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.movenext
loop 
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.

Related