Find RegExp matching text next to my cursor in Google Docs?

I have a document with text that can be matched with this regular expression. I would like to find the text next to the cursor in Google Docs that matches this regular expression and add a hyperlink to it.

The problem is that for some reason the regex doesn't seem to find the text. As a result, I get errors because (materiality) it cannot add a hyperlink to "null".

Google Doc is here (some hyperlinks have already been added manually, I'm trying to automate it to make it easier to add).

This is the code I'm currently using:

function Insert_Link() {
  var doc = DocumentApp.getActiveDocument();
  var Title = doc.getName();
  var elements = doc.getCursor().getSurroundingText();
  var element = elements.findText(/\d(-|\d|:|;|,)+/);
  var startOffset = element.getStartOffset();
  var endOffset = element.getEndOffsetInclusive();
  var selection = element.asText();
  var selectedText = selection.getText();
  selectedText = selectedText.substring(startOffset, endOffset + 1).trim();
  var reference = Title.replace(/(\(.*\))/, "").replace(/^\d{1,2}/, "") + " " + selectedText;
  Ref2Link(reference, selection, startOffset, endOffset);
}

, - , , . - , , .

+4
2
0

findText() :

JavaScript , .

, searchPattern , String, RegExp. (Tricky!)

RegExp . :

var element = elements.findText("\d[-\d:;,]+");
+4

Source: https://habr.com/ru/post/1619505/


All Articles