簡體   English   中英

Google Apps 腳本用動態 URL 替換文本

[英]Google Apps Script Replace Text With Dynamic URL

我希望能夠找到詳細說明 Jira 票證 ID(即TICKET-123 )的文本,並讓腳本能夠將該文本替換為實際票證的相關 Jira 鏈接(即https://jira.com /瀏覽/TICKET-123 )。 我不確定如何處理通配符和動態 URL 替換。

這就是我現在所處的位置 - 我可以在我的文檔中找到文本TICKET-123並將其轉換為標題為“TICKET-123”的超鏈接,但超鏈接路徑不包含完整路徑。 URL 最終只是https://jira.com/browse/TICKET- 我錯過了什么? 如何將這些相關的三個數字添加到路徑的末尾?

 function singleLinkWithinParagraph(){ // ## Inputs ## let textToFind = "TICKET-"; // this is what to look for let text = textToFind; // this is what the URL title will be let url = "https://jira.com/browse/"; // this is the actual link // ############ let body = DocumentApp.getActiveDocument().getBody(); let foundText = body.findText(textToFind); // Get the start and end location of the text in the paragraph. let startText = foundText.getStartOffset(); let endText = startText + text.length + 2; // Get the element indext for this section of text. let element = foundText.getElement(); // Replace the text and insert the URL. element.asText().replaceText(textToFind, text).setLinkUrl(startText, endText, url); };

我相信你的目標如下。

  • 您想從 Google 文檔中搜索TICKET-123之類的文本,您想將https://jira.com/browse/TICKET-123之類的超鏈接反映到搜索的文本中。
  • 在您的 Google 文檔中,有幾個文本,例如TICKET-###

在這種情況下,下面的修改腳本怎么樣?

修改后的腳本:

function singleLinkWithinParagraph() {
  let textToFind = "TICKET-\\d+"; // this is what to look for
  let url = "https://jira.com/browse/"; // this is the actual link
  let body = DocumentApp.getActiveDocument().getBody();
  var s = body.findText(textToFind);
  while (s) {
    var start = s.getStartOffset();
    var text = s.getElement().asText().getText().match(new RegExp(textToFind))[0];
    s.getElement().asText().setLinkUrl(start, start + text.length - 1, url + text);
    s = body.findText(textToFind, s);
  }
}
  • 在此修改中, TICKET-###的文本由TICKET-\\d+的正則表達式搜索。 找到文本時, https://jira.com/browse/TICKET-###的 URL 反映在搜索到的文本中。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM