Home Articles My Account Messages Tools Join
Tech Blog, ASP.Net, VB.Net, C#.Net, Programming Help, Help Guide
StellarPC.com | Using the Replace Function for strings (VB.Net)
Using the Replace Function for strings (VB.Net)
Written by: Justin Rich

Using the Replace Function for strings

Quite possibly one of the most used functions in string manipulation besides Trim. I'm going to try to cover all string manipulation eventually. The replace function is very handy especially when we're doing ASP.Net. Many times you're converting data out of a database and presenting it on a webpage. When you're converting that data, you may need to switch out some of the text with different text. For instance, you will want to Replace the hard returns in the data with "<br>" tags. These tags are the line breaks in HTML if you don't know. There are many reasons to do it... lets say we're doing a SQL query and you know that the string data has a single apostrophe in it ('). In SQL (Structured Query Language) you have to do double apostrophes so that the query knows you intend to have the apostrophe in the query string. Enough about reasons to use Replace...

The functional way to do this is this:
strResult = Replace(strData, "find", "replace")


This is the legacy way to do it where you are calling the replace function, passing the string you want to do the replace on, passing the string you want to find and then passing the string you want to replace. Finally, you're setting the return back to another string (it can be the same string if you wish).

Another (updated) way of doing this in .Net is this:\
strData.Replace("find", "replace")


Here, the compiler already knows that strData is a string, so the Replace function is now a Property of the string. Then, you don't have to pass the string as a parameter, and all you need to pass is the find & replace strings.

Dim strData as String = "This is a basic string."

strData.Replace("basic", "very complex")

Response.Write(strData)


The result will be this:
This is a very complex string.
New Post Next 50 | Previous 50
Post# Subject: Posted By: Time:
New Post Next 50| Previous 50