Search code examples
vbscriptsplitasp-classicchunks

splitting a string in chunks using classic asp


i got a list coma separated values (a,b,c,d,e,f,g,h,....) i wish to split them into chunks of 5 like (a,b,c,d,e) (f,g,h,i,j).... can someone help me with the code in classic asp ?

arr = Split(messto, ",") ' convert to array
totalemails = UBound(arr) ' total number of emails

if totalemails mod 5 = 0 then
    totalloops = int(totalemails/5) 
    else
    totalloops = int(totalemails/5) + 1
end if

x = 0 
y = 0
b = 0
for x = 0 to totalloops  


    for counter = (5* x)  to ((b+5)-1)
        if Trim(arr(counter)) <> "" and isnull(trim(arr(counter))) = false then 

        response.Write(Trim(arr(counter)))
        response.Write(counter & "<br>")
        mymssto =  mymssto & Trim(arr(counter)) & ","
        response.Write(mymssto)

        end if  

    next

Solution

  • You want to use Mod() to do this it's very powerful and underutilised function.

    Here is a simple example based on the code in the question;

    <%
    Dim mumberToGroupBy: numberToGroupBy = 5
    Dim index, counter, arr, messto
    
    messto = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q"
    arr = Split(messto, ",") ' convert to array
    
    For counter = 0 To UBound(arr)
      'Can't divide by 0 so we need to make sure our counter is 1 based.
      index = counter + 1
      Call Response.Write(Trim(arr(counter)))
      'Do we have any remainder in the current grouping?
      If index Mod numberToGroupBy = 0 Then Response.Write("<br>")
    Next
    %>
    

    Output:

    abcde
    fghij
    klmno
    pq
    

    Useful Links