Build an ONLYOFFICE macro that adds comments to every instance of a word in the Text Editor
Published: 2023-12-06 19:07:10

When working on documents, there are times when it’s essential to include a comment for a specific word that appears repeatedly throughout the text.  In this blog-post, we will show you how you can efficiently add comments to every instance of a specific word, streamlining your editing process and enhancing document clarity.

---

## Building the macro

`function addCommentToWord() {`

The _addCommentToWord()_ function is designed to add comments to every occurrence of a specified word within the document.

Here’s a breakdown of its key components:

`   const oDocument = Api.GetDocument();
   const numberOfElements = oDocument.GetElementsCount();`

Here, we get the current document in the _oDocument_ variable. Next, we get all the elements in the document using the _GetElementsCount()_ method.

 `   for (
        let elementIndex = 0;
        elementIndex < numberOfElements;
        elementIndex++
      ) 
`
A _for loop_ is used here to _iterate_ through all the elements. Doing this adds a comment to the desired word in every element (paragraph) of the document.

`{
        const oElement = oDocument.GetElement(elementIndex);
        const rawText = oElement.GetText();`

Inside the for loop, we get each element of the document by the _GetElement_ method and passing in the _elementIndex_ . Then, we extract the plain text in the _rawText_ variable.

`    const targetWord = "sample word";
    let count = 0;
    for (let i = 0; i < targetWord.length; i++) {
      count++;
    }
    const wordLength = count - 1;
`
Here, we set the word we want our comments to be on. Next, we calculate the length of the word using a _for loop_, and store it in _wordLength_.

` const wordRegex = new RegExp("\\b" + targetWord + "\\b", "gi");
`
Then, a regular expression (_wordRegex_) is created using the target word to find all occurrences in the document.

`let match;
    while ((match = wordRegex.exec(rawText)) !== null) {
      let matchPosition = match.index; 
      let nextMatchPosition = matchPosition + wordLength;
      const comment = "YOUR COMMENT GOES HERE";
      const oParagraph = oDocument.GetElement(0);
      const range = oParagraph.GetRange(matchPosition, nextMatchPosition);
      range.AddComment(comment, "Comment's Author Name");
       }
    } 
  }
`
Here, inside a _while loop_, we _iterate_ through all the instances found and stored in _wordRegex_. 
For each match, the starting position of the word (_matchPosition_) and the position of the next character after the word (_nextMatchPosition_) are calculated. 
The _comment_ variable holds the comment you want to insert. The _AddComment_ method has an optional parameter which can be used to alter the author’s name. If you don’t want to use it, you can exclude the optional parameter, and just pass in the comment variable.

`addCommentToWord();
`
Finally, the _addCommentToWord_ function is called.

## The full macro code
Here is the enitre code of the macro:

```
(function () {
  function addCommentToWord() {
    const oDocument = Api.GetDocument();
    const numberOfElements = oDocument.GetElementsCount();

    //looping through all the elements in the document.
    for (
        let elementIndex = 0;
        elementIndex < numberOfElements;
        elementIndex++
      ) {
        const oElement = oDocument.GetElement(elementIndex);
        const rawText = oElement.GetText();
  
      // Specify the target word and the length of the word
      const targetWord = "sample word";
      let count = 0;
      for (let i = 0; i < targetWord.length; i++) {
        count++;
      }
      const wordLength = count - 1;

      // Find all occurrences of the target word in the document
      const wordRegex = new RegExp("\\b" + targetWord + "\\b", "gi");
      let match;
      while ((match = wordRegex.exec(rawText)) !== null) {
        
        let matchPosition = match.index; // returns the index where the word starts.
        let nextMatchPosition = matchPosition + wordLength; //the index where the word ends.

        // Add a comment at the position of the match
        const comment = "YOUR COMMENT GOES HERE";
        const range = oElement.GetRange(matchPosition, nextMatchPosition);
        range.AddComment(comment, "Comment's Author Name");
      }
    }
  }

  addCommentToWord();
})();

```
Now, let us see how our macro performs.

{% embed https://www.youtube.com/watch?v=dy-QRGM7Hpo %}
I trust this macro made handling repetitive word comments a breeze, providing a handy tool for users dealing with the document editor in ONLYOFFICE.
Don’t miss the chance to harness the power of the ONLYOFFICE API.  If you have any questions or innovative concepts, I encourage you to [share them with the ONLYOFFICE Team](https://www.onlyoffice.com/contacts.aspx?utm_source=blog&utm_medium=article+&utm_id=comment_word_macro). Best of luck in your exploratory endeavors!

**<u>Useful links</u>**

[Macro samples](https://api.onlyoffice.com/plugin/macrosamples/?utm_source=blog&utm_medium=article+&utm_id=comment_word_macro)

[ONLYOFFICE on GitHub](https://github.com/ONLYOFFICE)

[ONLYOFFICE Text Document API](https://api.onlyoffice.com/docbuilder/textdocumentapi?utm_source=blog&utm_medium=article+&utm_id=comment_word_macro)

[Other macros](https://www.onlyoffice.com/blog/search?s=macro&utm_source=blog&utm_medium=article+&utm_id=comment_word_macro)

---

## About Me
I am Eeshaan, a senior studying Computer Science in Pune, India. I am fond of Open-Source, Web Development, and Technical Writing. Feel free to give me a follow on my [Twitter (now X)](https://twitter.com/sawanteeshaan), if my blog was of any use to you. Cheers. 🍻