stringvbscriptasp-classic

How do you replace the last comma with "and" in a comma-separated string?


I need to use VBScript to insert an "and" into a string before the last item in a comma-separated list.

strList = "512, 66, 1820, 1235, 7, 4918"

needs to become...

strReList = "512, 66, 1820, 1235, 7 and 4918"

I've looked around SO and have found this question answered for javascript, C# and other languages, but never VBS.


Solution

  • This can be achieved with the StrReverse() and Replace() functions:

    Option Explicit
    Dim strList: strList = "512, 66, 1820, 1235, 7, 4918"
    strReList = StrReverse(strList)
    strReList = Replace(strReList, ", ", " dna", 1, 1)
    strList = StrReverse(strReList)
    Call Response.Write(strList)
    

    Output:

    512, 66, 1820, 1235, 7 and 4918