ASP Code

Mimic PHP's str_pad() function with ASP

PHP has a handy function called str_pad(). You send a string to the function with the desired length, and it appends spaces or any specified characters to the string until reaching that length. You have the options of specifying where to pad (left, right, or both). Here is the equivalent in ASP.
There are two functions in the code that may be foreign, (isTrulyNumeric & errorMessage). You can find them explained here.

Function strPad( strToPad, toLength, padWith, padWhere )
    'padWhere: 1=right, 2=left, 3=both
    strToPad = strToPad & ""
    dim padBoth
    padBoth = false
    if not isTrulyNumeric( toLength ) then
        call errorMessage( "Desired length not specified!")
         toLength = cint( toLength )
    end if
    if padWith = "" then padWith = " "
    if not isReallyNumeric( padWhere ) then   
        padWhere = 1
         padWhere = cInt( padWhere )
        if padWhere > 3 or padWhere < 1 then padWhere = 1
         if padWhere = 3 then
            padBoth = true
            padWhere = 1
        end if
    end if
    do until len( strtoPad ) >= toLength
        select case padWhere
         case 1
             strtoPad = strtoPad & padWith
         case 2
             strtoPad = padWith & strtoPad
        end select
        if padBoth then
            if padWhere = 1 then
                padWhere = 2
                 padWhere = 1
            end if
        end if
    if len( strToPad ) > toLength then
        if ( padBoth and padWhere = 1 ) or ( padWhere = 2 and not padBoth ) then '=== no carriage return here
            strToPad = right( strToPad, toLength )
            strToPad = left( strToPad, toLength )
        end if
    end if
    strPad = strToPad
End Function


  1. Man, that's a great function!
    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image