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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.