When reviewing a long document, the find and highlight feature allows users to quickly locate specific information. For example, if there are multiple people working on a research paper, the find and highlight feature can be used to flag important points or areas that need attention, making it easier for others to focus on those specific parts. This article will demonstrate how to find and highlight text in a Word document in React using Spire.Doc for JavaScript.
- Find and Highlight the First Instance of Specified Text in Word
- Find and Highlight All Instances of Specified Text in Word
Install the JavaScript Library
To get started with inserting images in Word in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.office
The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Find and Highlight the First Instance of Specified Text in Word in JavaScript
The Document.FindString() method allows to find the first instance of a specified text and then you can set a highlight color for it through the TextRange.CharacterFormat.HighlightColor property. The following are the main steps:
- Create a new document using the new wasmModule.Document() method.
- Load a Word document using the Document.LoadFromFile() method.
- Find the first instance of a specific text using the Document.FindString() method.
- Get the instance as a single text range using the TextSelection.GetAsOneRange() method, and then highlight the text range with a background color using the TextRange.CharacterFormat.HighlightColor property.
- Save the result document using Document.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to find and higlight a specified text in Word
const FindHighlightFirst = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const inputFileName = 'input.docx';
const outputFileName = 'FindHighlightFirst.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Find the first instance of a specific text
let textSelection = doc.FindString('Spire.Doc for JavaScript', false, true);
// Get the instance as a single text range
let textRange = textSelection.GetAsOneRange();
// Set highlight color
textRange.CharacterFormat.HighlightColor = wasmModule.Color.get_Yellow();
// Save the result document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated Word file from VFS
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the Word file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement("a");
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Find and Highlight Specified Text in Word Using JavaScript in React</h1>
<button onClick={FindHighlightFirst} disabled={!wasmModule}>
Execute
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Execute" button to download the result file:

The result file:

Find and Highlight All Instances of Specified Text in Word in JavaScript
Spire.Doc for JavaScript also provides the Document.FindAllString() method to find all instances of a specified text in a Word document. Then you can iterate through these instances and highlight each one with a background color. The following are the main steps:
- Create a new document using the new wasmModule.Document() method.
- Load a Word document using the Document.LoadFromFile() method.
- Find all instances of a specific text in the document using the Document.FindAllString() method.
- Iterate through each found instance and get it as a single text range using the TextSelection.GetAsOneRange() method, then highlight each text range with a bright color using the TextRange.CharacterFormat.HighlightColor property.
- Save the result document using Document.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to find and higlight a specified text in Word
const FindAndHighlightAll = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const inputFileName = 'input.docx';
const outputFileName = 'FindAndHighlight.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Find all occurrences of the specified text in the document
let textSelections = doc.FindAllString('Spire.Doc for JavaScript', false, true);
// Iterate through all found text selections
for (let i = 0; i < textSelections.length; i++) {
let selection = textSelections[i];
// Set highlight color
selection.GetAsOneRange().CharacterFormat.HighlightColor = wasmModule.Color.get_Yellow();
}
// Save the result document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated Word file from VFS
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the Word file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement("a");
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<<div style={{ textAlign: 'center', height: '300px' }}>
<<h1>Find and Highlight Specified Text in Word Using JavaScript in React<</h1>
<<button onClick={FindAndHighlightAll} disabled={!wasmModule}>
Execute
<</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.