tlewis3348
tlewis3348

Reputation: 486

Find text matching a RegExp near my cursor in Google Docs?

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

The problem is that for whatever reason, the regular expression does not seem to be finding the text. As a result, I'm getting errors because (essentiality) it can't add a hyperlink to "null".

The Google Doc is here (some hyperlinks have been already added manually, I'm trying to automate it so it's simpler to add them).

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);
}

I'm sure I'm making some stupid mistake, but I can't tell what that is. If anyone can tell me what I'm doing wrong, I'd greatly appreciate it.

Upvotes: 4

Views: 223

Answers (2)

marukou
marukou

Reputation: 16

please change '\' to double '\'.

I change your Doc's code too.

Please try it.

ref:Special Characters (JavaScript)

https://msdn.microsoft.com/en-us/library/2yfce773(v=vs.94).aspx

Upvotes: 0

Mogsdad
Mogsdad

Reputation: 45750

The documentation for findText() says:

A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.

Further, searchPattern is supposed to be a String, not a RegExp. (Tricky!)

Your RegExp includes a capture group. This one will match the same groupings, without a capture group:

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

Upvotes: 3

Related Questions