Trim 字符串末尾的最后一个字符

Trim the last character at the end of string

我有一个循环,它在文件末尾创建一个字符串。取决于我当时有多少产品。我需要 trim 最后一个逗号。

我得到:

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

我需要:

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

循环:

<%
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 
%>

将你的逗号移到循环的开头并将其放在条件语句中,这样它就不会在第一次迭代时执行

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 

多年来发现最简单的方法是让循环在使用 Left().

执行循环后生成比 trim 额外的字符

循环后添加;

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

这种方式避免了在循环中添加大量逻辑来处理不必要的边缘情况。

在这种情况下我经常使用Join方法

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,",")

如果您不想使用 Arraylist,您可以对普通数组执行相同的操作,但每次迭代都必须重新调整它。