How to Replace a String in a Word Document using Node.js

Cloudmersive
2 min readDec 6, 2023

--

Making programmatic changes to DOCX files is extremely easy thanks to the simplicity and accessibility of OpenXML formatting.

In fact, we can make quick changes to DOCX documents in our Node.js applications without writing any new code at all. Using the complementary, ready-to-run code examples below, we can take advantage of a free API that replaces strings in a DOCX document with a new string value. We can base our operation on form data OR a file URL, and our operation will return the encoding for our updated DOCX file.

To authorize our request, we’ll just need a free-tier API key, which we can get by registering a free account on the Cloudmersive website.

Our first step is to install the SDK. We can do so either by running the below command:

npm install cloudmersive-convert-api-client --save

Or by adding the below snippet to our package.json:

  "dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}

After that, we can copy the below code into our file and customize our requests:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveConvertApiClient.TransformDocumentApi();

var matchString = "matchString_example"; // String | String to search for and match against, to be replaced

var replaceString = "replaceString_example"; // String | String to replace the matched values with

var opts = {
'inputFile': Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer), // File | Optional: Input file to perform the operation on.
'inputFileUrl': "inputFileUrl_example", // String | Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API (part of EditDocumentApi) to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public).
'matchCase': true // Boolean | Optional: True if the case should be matched, false for case insensitive match. Default is false.
};

var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.transformDocumentDocxReplace(matchString, replaceString, opts, callback);

That’s all there is to it — no more code required!

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet