Tuesday, October 03, 2006

Using the VBScript Replace() Function in ASP

Ever wanted to search a string to find a word or phrase and replace it with a different word or phrase? ASP in VBScript provides an extremely useful and easy to use function - Replace() - that can be used replace all occurrences of a particular substring with a replacement substring.

Here's the format:
Replace(String, Find, ReplaceWith[, start[, count[, compare]]])
String is the original string

Find is the substring you are searching for

ReplaceWith is what you want to replace the substring with.

Find and replaceWith are the only required parameters.

There are some optional parameters as well:
start is the position in the original string where you want to start your seach from (default is 1)

count is the number of occurances you want to replace (default is -1, which means all occurances)

compare determines the mode to use when doing the comparison. vbBinaryCompare is case sensitive, vbTextCompare is not. By default, it is set to vbBinaryCompare

The compare variable is worth looking at more in-depth. Example:
Replace("quick brown fox", "Fox", "Dog")
If you execute this, the result with be "quick brown fox". The replace won't happen because by using the default, vbBinaryCompare, "Fox" does not equal "fox": the case of the 'f' is different.

If you want the replace to be case insensitive, you have to execute it as:
Replace("quick brown fox", "Fox", "Dog", vbTextCompare)
In this example, the result will be "quick brown Dog". It will ignore case when searching for "fox" and will replace it with the substring you specified, in this case "Dog" with a capital "D".

Another way to do this is to use LCase() to make the string all lower case:
Replace(LCase("quick brown FOX"), "fox", "DOG")
The result here would be "quick brown DOG".

Replace() is very useful for manipulating strings, but if you don't know how to set your case sensitivity, it can be frustrating!


Anonymous said...

Thanks a lot,
This trick saves me a lot of time ...

Tom said...

I could only get the vbTextCompare to work by including the 1 and -1 along before it.. i.e. with the example above, Replace("quick brown fox", "Fox", "Dog", vbTextCompare) should become: Replace("quick brown fox", "Fox", "Dog", 1, -1, vbTextCompare).



Anonymous said...

I just wanted to replace a " ' " with a string as it was going in a database.