Skip to main content

Replace words in document

Searches for a word throughout the document and replaces it with the given replacement word.

(function () {
let doc = Api.GetDocument();
let range = doc.GetRangeBySelect();
let rawText = range.GetText();
range.Delete();
// Define the word to find and the word to replace it with
let wordToFind = "oldWord"; // Replace "oldWord" with the word you want to find
let replacementWord = "newWord"; // Replace "newWord" with the word you want to replace it with
// Use regular expression to find and replace the word
let cleanedText = rawText.replace(
new RegExp(wordToFind, "g"),
replacementWord
);
// Insert the cleanedText with the original paragraph structure
let paragraph = Api.CreateParagraph();
paragraph.AddText(cleanedText);
doc.InsertContent([paragraph]);
})();

Methods used: GetDocument, GetRangeBySelect, GetText, Delete, CreateParagraph, AddText, InsertContent

Reference Microsoft VBA macro code

Sub SimpleFindReplace()
Selection.Find.Execute FindText:="find", ReplaceWith:="replace", Replace:=wdReplaceAll
End Sub

Result

Replace Words in DocumentReplace Words in Document