google-apps-scriptgoogle-docs

Google Script Select Partial Text in Docs


My goal is to build a system that selects whitespace that has been underlined, and so far I have a system that moves the cursor to the start of the underlined section and highlights it.

I'm new to using Google's Apps Script, and have gotten stuck trying to programmatically select only part of a paragraph. I've figured out how to select an entire paragraph and how to move the cursor to a specific location within a paragraph, but I can't figure out how to only select part of a paragraph; partially highlighted text.

I've tried using var range = DocumentApp.getActiveDocument().newRange(); and DocumentApp.getActiveDocument().setSelection(range.build());, but this only selects entire paragraphs, not small portions of them.

Is there a way to select text in a paragraph between a start point and and end point?


Solution

  • I believe your goal is as follows.

    About I've tried using var range = DocumentApp.getActiveDocument().newRange(); and DocumentApp.getActiveDocument().setSelection(range.build());, but they only select entire paragraphs, not small portions of them., I think that an error occurs in your script, because no range is included. In this case, it is required to include the range.

    The sample script is as follows. In this case, a part of text in a paragraph is selected using the method of addElementsBetween(startTextElement, startOffset, endTextElementInclusive, endOffsetInclusive) of Class RangeBuilder.

    Sample script:

    Please copy and paste the following script to the script editor of Google Document. And, please set start and end. In this sample script, a part of the text in 1st paragraph is selected using a script.

    function myFunction() {
      const start = 8; // Please set the start offset.
      const end = 14; // Please set the end offset.
    
      const doc = DocumentApp.getActiveDocument();
      const paragraph = doc.getBody().getParagraphs()[0]; // As a sample, the 1st paragraph is used.
      const text = paragraph.editAsText();
      const range = doc.newRange().addElementsBetween(text, start, text, end).build();
      doc.setSelection(range);
    }
    

    Testing:

    When this script is used, the following result is obtained.

    From:

    enter image description here

    To:

    enter image description here

    Note:

    References: