How to Replace a String in a Word DOCX File using Node.js

Cloudmersive
2 min readNov 1, 2023

--

Making changes to text content in DOCX documents through a Node.js application — especially standardized content like contracts, invoices, etc. — is surprisingly easy to accomplish with a quick API request.

Using the below code, we can take advantage of a free API that will replace specific input strings in a DOCX file with a new string value. We just need to supply our matchString (the string to match against and replace) and our replaceString (the string to replace matched values with), and our response will contain the encoding for our updated file.

We can structure our API call in a few quick steps. Let’s first install the SDK — either by running the following command:

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

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

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

Then, let’s include the below ready-to-run code in our file, and let’s authorize our request by supplying a free-tier Cloudmersive API key in the authorization snippet (these allow up to 800 API calls per month with no commitment). We can pass our file via path or URL, and we can also specify if we want case matching to factor into our string match request via the optional matchCase parameter:

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