O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Replace All Occurrences of Specific Text in a String

Problem

You want to replace a certain word or sequence of characters each time it occurs in a string.

Solution

Use the String.Replace method.

Discussion

The String class provides a Replace method that replaces all occurrences of text inside a string, and returns a new string:

Dim Text As String = "The quick brown fox jumps over the lazy dog. " & _
  "The quick brown fox jumps over the lazy dog. " & _
  "The quick brown fox jumps over the lazy dog. "

Dim ReplacedText As String = Text.Replace("brown", "blue")
' ReplacedText is now "The quick blue fox jumps over the lazy dog."
' repeated identically three times.

If you want to replace the occurrence of a pattern in just a portion of the string, you will need ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required