find_and_replace
Locate and substitute text in Word documents to update content, correct errors, or modify formatting across specified sections or the entire file.
Instructions
Find and replace text in the document
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| docId | Yes | Document identifier | |
| findText | Yes | Text to find | |
| replaceText | Yes | Text to replace with | |
| replaceAll | No | Replace all occurrences (true) or just first (false) |
Implementation Reference
- src/tools/document-tools.ts:145-171 (registration)Tool registration including name, description, and input schema for find_and_replace{ name: "find_and_replace", description: "Find and replace text in the document", inputSchema: { type: "object", properties: { docId: { type: "string", description: "Document identifier", }, findText: { type: "string", description: "Text to find", }, replaceText: { type: "string", description: "Text to replace with", }, replaceAll: { type: "boolean", description: "Replace all occurrences (true) or just first (false)", default: true, }, }, required: ["docId", "findText", "replaceText"], }, },
- src/tools/tool-handlers.ts:73-87 (handler)Main tool handler switch case that processes find_and_replace tool calls by invoking documentManager.findAndReplace and formatting the responsecase "find_and_replace": const count = documentManager.findAndReplace( args.docId, args.findText, args.replaceText, args.replaceAll ?? true ); return { content: [ { type: "text", text: `Replaced ${count} occurrence(s) of "${args.findText}" with "${args.replaceText}".`, }, ], };
- Core implementation of find and replace logic that iterates through document paragraphs, performs replacements on TextRun elements, counts occurrences, and updates the documentfindAndReplace( docId: string, findText: string, replaceText: string, replaceAll: boolean = true ): number { const docInfo = this.getDocument(docId); let replacementCount = 0; docInfo.paragraphs.forEach((paragraph: any) => { if (paragraph.root && paragraph.root.length > 0) { paragraph.root.forEach((element: any) => { if (element.text) { if (replaceAll) { const regex = new RegExp(findText, "g"); if (regex.test(element.text)) { const matches = element.text.match(regex); replacementCount += matches ? matches.length : 0; element.text = element.text.replace(regex, replaceText); } } else { if (element.text.includes(findText) && replacementCount === 0) { element.text = element.text.replace(findText, replaceText); replacementCount = 1; } } } }); } }); this.updateDocument(docId); return replacementCount; }