Search code examples
stringvbscriptasp-classic

Insert a character into a string at a specified index


So I have an array of indexes of characters in a string that I wish to insert a character before, how do i easily insert a character before each index? So for example:

"The big brown fox ... "

the positions array = 4,9

the character to insert ','

the result: "The, big, brown fox ..."

Is there a method that provides such an easy utility?

String.insert(originalStr, index, stringToInsert) for example???


Update

The example I provided is just an example implementation. I also may want to do the following:

orginalText = "some text with characters like ; : } <"

in which I may want to insert "\" with the result being:

result = "some text with characters like \; : } \<"


Solution

  • This is hacky and a bit rushed but try this:

    Dim sString: sString = "the something something"
    Dim position: position = 1
    Dim character: character = "F"
    if position = 0 then
        sString = character + Left(Mid(sString, 1), Len(sString) + 1)
    else
        sString = Left(sString, position) + character + Left(Mid(sString, position), Len(sString) - position + 1)
    end if