Replace Text with New Text in Word in Java

This article demonstrates how to replace text with new text in a Word document using Spire.Doc for Java.

We can replace a specified text with new text by using the replace method of the Document class:

import com.spire.doc.*;

public class ReplaceText {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document("Input.docx");
        
        //Replace the specified text with new text 
        document.replace("Spire.Doc for Java", "NewText", false, true);
        
        //Save the document
        document.saveToFile("ReplaceAllMatchedText.docx", FileFormat.Docx_2013);
    }
}

Replace Text with New Text in Word in Java

The above example replaces all of the "Spire.Doc for Java" text that exists in the Word document. We can also specify to replace only the first occurrence of the specified text by using the setReplaceFirst method of Document class:

import com.spire.doc.*;

public class ReplaceText {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document("Input.docx");
        
        //Set to replace only the first occurrence of the specified text
        document.setReplaceFirst(true);

        //Replace with new text
        document.replace("Spire.Doc for Java", "NewText", false, true);
        
        //Save the document
        document.saveToFile("ReplaceFirstMatchedText.docx", FileFormat.Docx_2013);
    }
}

Replace Text with New Text in Word in Java