'' This code is part of GrapeCity Documents for Word samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
Imports System.IO
Imports System.Drawing
Imports System.Text
Imports System.Text.RegularExpressions
Imports GrapeCity.Documents.Word

'' This sample loads an existing document, finds all occurrences
'' of a certain string in it, And replaces that string with another one.
'' Note that this code only finds occurrences of the search string
'' that are completely within a single run. To find strings spanning
'' two Or more runs (e.g. if different parts of the string have
'' different formatting) will require a more complex searching logic.
'' For a similar sample that also changes the formatting of the
'' replacement, see ReplaceTextFmt.
Public Class ReplaceText
    Public Function CreateDocx() As GcWordDocument
        '' The document to replace text in:
        Dim path = System.IO.Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx")
        '' The text to find
        Const tFind = "javascript"
        '' The replacement
        Const tRepl = "ArabicaScroll"

        Dim doc = New GcWordDocument()

        '' Loop over all texts in the document body
        For Each text In doc.Body.Texts
            If TypeOf (text) Is Break Then
                Continue For
            End If

            Dim str = text.Value
            Dim matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase)
            If matches.Count = 0 Then
                Continue For
            End If

            Dim sb = New StringBuilder()
            Dim pos = 0
            For Each m In matches
                sb.Append(str.Substring(pos, m.Index - pos))
                pos = m.Index + m.Length
            text.Value = sb.ToString()

        '' Add a note at the end of the document:
        $"GcWord replaced '{tFind}' with '{tRepl}' on {DateTime.Now}.")

        '' Done
        Return doc
    End Function
End Class