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

76 Views Asked by At

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.

2

There are 2 best solutions below

0
nbardach On BEST ANSWER

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
1
alex-dl On

Using a regular expression:

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

Set rx = New RegExp
rx.Pattern = "(.*),\s*(\d+)"
strListMod = rx.Replace(strList, "$1 and $2")

wscript.echo strListMod

Output:

512, 66, 1820, 1235, 7 and 4918