Searching and replacing strings inside another string using VBScript in ASP
We can search a string for presence of another string and replace it with a string by using Replace function of VBScript in ASP. This function search for the given string and replace it with another string. The search condition can be changed with optional arguments. We can also control with number of search and replace or replace all with matching strings. Here is the syntax of Replace() function.
Replace(string_var, string_find, string_replace, start, count, comparetype)
Here inside replace function string_var is the main string inside which we will search for the string string_find and if found then it will be replaced with the string string_replace. Other arguments like start, count and comparetype are optional arguments. The argument start specifies from where the search and replace should start. The argument count specifies how many times the given search and replace operation has to work. The argument comparetype can take value of 0 and 1, here 0 means ( by default it is zero ) it is binary comparison so case sensitive as a result lower case text are different than upper case text. If the value of comapretype is set to 1 then it is a text comparison and lower case letters are treated same as upper case letters ( case insensitive ).
Here is a simple code example of Replace function.
The output of the above code is here
string_var="Welcome to ASP section for ASP tutorials"
Welcome to PHP section for PHP tutorials
You can see all the occurrences of the string ASP is replaced with PHP ( here in two places )
The above code let us modify to experiment with different argument values. Let us try with lower case words. The following one lines we will replace in the above code.
The output of this replacement is here
Welcome to ASP section for ASP tutorials
You can see there is no replacement of the word as now the Replace function is case sensitive ( as comparetype value is set to 0 by default ). Now let us change the Replace function with more arguments like this.
The output of above replacement is here
Welcome to PHP section for ASP tutorials
As you can see the arguments have values like
As count = 1 so the replace function will replace ASP with PHP once only. Here we have set comparetype to 1 so this is a case insensitive search operation so the string value asp is same as ASP.
So for your practice you can experiment with different value of arguments to learn how the Replace function works in different combinations.
In PHP similar function is str_replace()
Be the first to post comment on this article :