In a Word Add-In using the JS API, how to update a text by adding/removing certain parts?

Roland 0 Reputation points
2024-07-16T22:09:02.1133333+00:00

We've built an Office Add-in for Word, and would like to build the following:

  • User selects one or more paragraphs.
  • They click a button in our add-in.
  • This will send the text to our API which returns an updated version of these paragraphs.
  • It should display to the user which words have been added/removed, preferably using Tracked Changes.

Just an example:

Original text: BankA a [Specify State] banking institution, with its principal place of business located at [Address] ("Banker").

New text:

LenderC a [Specify State] lending institution, lending laws apply, with its principal place of business located at [Address] ("Lender")

E.g. "BankA" should be deleted, "LenderC" added, "lending laws apply" added, and so on.

When I just delete all paragraphs & replace it with the new text, it shows all the old text as deleted and the new text as added. That's not what we want.

So, we need to be smarter and only update the differences. I've found this library which gives me all additions and deletions: https://github.com/kpdecker/jsdiff

I plan to loop over all changes, and act accordingly. I've tried it with a basic example, but run into some issues:

  • I keep track of the current character index to perform the required action (delete/add). The JS API doesn't allow character based indexes by default, so I use this workaround: https://stackoverflow.com/posts/71824284/revisions
    However, that is error prone, after ~2 additions it was already one character off.
  • I also looked at the "search" method, but that doesn't allow me to set a start index. That is needed in case a deleted word appears more than once.

Essentially, we're looking for what the "Document Compare" function is doing. This is currently in preview so unsure when we can use this in production. Is that our best bet? It requires an external document, so I'd have to create the second document first to be able to compare it to the current document.

Perhaps I'm on the wrong track and doing this too complicated. Any thoughts or tips?

Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,915 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.