How to do ‘replaceall’ in VBScript?

Posted by on Nov 13, 2010 in VBScript | 1 comment

As you might know the vbscript replace function does always search only “one round”. Here is an example, what exactly I mean:

Lets assume you want to correct the following string by replacing all “double-l’s” by “single-l’s”:

str = "Littllllle worllllllld!"

The code would be:

wscript.echo replace(str, "ll", "l")

But everything this line does is replace all existing “ll” by “l”. So lets have a look what’s left – the output is: Litllle worlllld!
Why? The original string contained 5 l in Little and 7 l in world. The function used replaces every ll, in Little there are 2 ll and 1 l, in world 3 ll and 1 l. After replacing all doubles you still have 3 l left in Little and 4 in world. As you can see replace only replaces existing strings, the lls that occur by replacing will not be touched… So you need to run a second round to replace more lls by ls…

Since I need this one very often, for example when replacing multiple new lines in html, I wrote a little function doing all the work for me. Here it is:

Function ReplaceAll(str, find, replacewith)
While InStr(str, find) > 0
str = Replace(str, find, replacewith)
Wend
ReplaceAll = str
End Function

One Comment

  1. When using this function always make sure, that your replacewith parameter never contains the find parameter or you are running into an infinite loop!

Leave a Reply

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

Captcha: * Time limit is exhausted. Please reload CAPTCHA.