Come aggiungere commenti a ogni occorrenza di una parola con le macro di ONLYOFFICE

5 gennaio 2024By Alice

Quando si lavora sui documenti, ci sono momenti in cui è essenziale includere un commento per una parola specifica che appare ripetutamente nel testo. In questo post del blog ti mostreremo come aggiungere in modo efficiente i commenti alle parole di cui hai bisogno, semplificando il processo di modifica e migliorando la chiarezza del documento.

Build an ONLYOFFICE macro that adds comments to every instance of a word in the Text Editor

Costruire la macro

function addCommentToWord() {

La funzione addCommentToWord() è progettata per aggiungere commenti a ogni occorrenza di una parola specificata all’interno del documento.

Ecco una ripartizione delle sue componenti fondamentali:

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

Qui otteniamo il documento corrente nella variabile oDocument. Successivamente, otteniamo tutti gli elementi presenti nel documento utilizzando il metodo GetElementsCount().

    for (
        let elementIndex = 0;
        elementIndex < numberOfElements;
        elementIndex++
      ) 

Per scorrere tutti gli elementi viene utilizzato un ciclo for. In questo modo si aggiunge un commento alla parola desiderata in ogni elemento (paragrafo) del documento.

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

All’interno del ciclo for, otteniamo ogni elemento del documento utilizzando il metodo GetElement e passando elementIndex. Quindi, estraiamo il testo normale nella variabile rawText.

    const targetWord = "sample word";
    let count = 0;
    for (let i = 0; i < targetWord.length; i++) {
      count++;
    }
    const wordLength = count - 1;

Impostiamo la parola dove vogliamo che appaiano i nostri commenti. Successivamente, calcoliamo la lunghezza della parola utilizzando un ciclo for e la memorizziamo in wordLength.

// Find all occurrences of the target word in the document
    const wordRegex = new RegExp("\\b" + targetWord + "\\b", "gi");

Quindi, viene creata un’espressione regolare (wordRegex) utilizzando la parola di destinazione per trovare tutte le occorrenze nel documento.

let match;
    while ((match = wordRegex.exec(rawText)) !== null) {
      let matchPosition = match.index; //returns the index where the word starts.
      let nextMatchPosition = matchPosition + wordLength;
      // Add a comment at the position of the match
      const comment = "YOUR COMMENT GOES HERE";
      const oParagraph = oDocument.GetElement(0);
      const range = oParagraph.GetRange(matchPosition, nextMatchPosition);
      range.AddComment(comment, "Comment's Author Name");
    } 
  }

Qui, all’interno di un ciclo while, iteriamo attraverso tutte le istanze trovate e archiviate in wordRegex.

Per ogni corrispondenza vengono calcolate la posizione iniziale della parola (matchPosition) e la posizione del carattere successivo dopo la parola (nextMatchPosition).

La variabile comment contiene il commento che vuoi inserire. Il metodoAddCommentha un parametro facoltativo che può essere utilizzato per modificare il nome dell’autore. Se non vuoi usarlo, puoi escludere il parametro facoltativo e passare semplicemente la variabile commento.

addCommentToWord();

Infine, viene chiamata la funzione addCommentToWord.

Il codice macro completo

Ecco l’intero codice della 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();
})();

Ora vediamo come funziona la nostra macro.

Confidiamo che questa macro abbia reso la gestione dei commenti verbali ripetitivi un gioco da ragazzi, fornendo uno strumento utile per gli utenti che hanno a che fare con l’editor di documenti in ONLYOFFICE.

Non perdere l’occasione di sfruttare la potenza dell’API ONLYOFFICE. La nostra vasta libreria di metodi API è la chiave per trasformare le tue idee in realtà. Se hai domande o concetti innovativi, ti invitiamo a condividerli con noi. Il tuo contributo è molto apprezzato e siamo entusiasti della possibilità di collaborare con te. Buona fortuna nell’esplorazione!