Updating Same Position on Google Document using Google Apps Script

Gists

This is a sample script for updating the same position on Google Document using Google Apps Script.

In this case, the named range is used. About the named range on Google Document, in the current stage, unfortunately, this cannot be used with the UI on Google Document. And, when I saw the official document of named range, I thought that this might be a bit difficult. Ref Ref So, I have created a Google Apps Script for managing the named range on Google Document. Ref In this post, I would like to introduce a sample script for updating the same position on Google Document using this GAS library.

Usage

1. Prepare Google Document.

In order to test this script, please create a new Google Document.

2. Sample script.

Please copy and paste the following script to the script editor of Google Document. And, please install the library.

const name = "sampleName"; // Sample name of named range.

const getAllNamedRanges_ = (doc) => {
  const obj = DocNamedRangeApp.getActiveDocument(doc).getAllNamedRanges();
  const ar = Object.entries(obj);
  if (ar.length == 0) return null;
  return ar.reduce((o, [k, v]) => ((o[v.name] = v.rangeElements), o), {});
};

// 1. First, set named range to the selected cotent.
function setNamedRange() {
  const doc = DocumentApp.getActiveDocument();
  DocNamedRangeApp.getActiveDocument(doc).setNamedRangeFromSelection(name);
}

// 2. When you want to update the text of the named range, please use this function.
function updateTextOfNamedRange() {
  const upadteText = "###"; // Please set the upate text.

  const doc = DocumentApp.getActiveDocument();
  const obj = getAllNamedRanges_(doc);
  if (!obj[name]) throw new Error("Please set named range.");
  obj[name][0].getElement().asText().replaceText(".*", upadteText);
}

3. Testing.

You can see the demonstration at the top image.

  1. Please select a text on Google Document. And, please run the function setNamedRange(). By this, the named range is set.
  2. When you update the text of named range, please run the function updateTextOfNamedRange(). By this, the text of named range is updated. In this case, even when the other parts are changed, the named range is preserved.

Note

  • When updateTextOfNamedRange() is modified to onOpen(), you can update the text of the named range when the Document is opened.

  • If you want to retrieve all named ranges, you can also use the following script.

    function getAllNamedRanges() {
      const doc = DocumentApp.getActiveDocument();
      const res = DocNamedRangeApp.getActiveDocument(doc).getAllNamedRanges();
      console.log(res);
    }
    
  • If you want to remove all named ranges, you can also use the following script.

    function deleteAllNamedRanges() {
      const doc = DocumentApp.getActiveDocument();
      const res = DocNamedRangeApp.getActiveDocument(doc).deleteAllNamedRanges();
      console.log(res);
    }
    

References

 Share!