从一串文本和超链接中提取指向 URL 和文本的超链接

Extract HyperLink to URL and Text from a string of text and hyperlink

我尝试搜索但找不到与我完全相同的人。 大多数仅对仅包含超链接的单元格进行操作。

我正在尝试编辑包含来自 Google Doc 的大量超链接和文本字符串的文章。我发现不可能仅在 Google Doc 中提取超链接和文本,所以我将其粘贴到 Google Sheets 中。

如何从一串文本 + 超链接中获取 URL 和锚文本?

https://docs.google.com/spreadsheets/d/1vuDGZ1l2rwqvpI6_fKWlUo4G9-hbAS6jI8XwhJSd8Ck/edit#gid=0

Sheet1!A1:B10 受到保护,以防有人搞砸它。

使用下面的函数。要 运行 它,您必须添加 Google Sheets API 服务。

function fillHyperlinks() {
  const ranges = "Sheet1!A6" // must be a single cell

  const ss = SpreadsheetApp.getActive() 
  const res = Sheets.Spreadsheets.get(ss.getId(), {ranges, fields: "sheets/data/rowData/values"});
  const rowData = res["sheets"][0]["data"][0]["rowData"]
  
  const result = []

  if(rowData.length>1 || rowData[0]["values"].length>1){
      throw new Error("the range must be a single cell")
  }
  
  const value= rowData[0]["values"][0]
  const runs = []
  const text = value["formattedValue"]
  const textFormatRuns = value["textFormatRuns"]
  let rows
  if(textFormatRuns){
    for(let r of textFormatRuns){
      const index = r.startIndex?r.startIndex:0
      if(runs.length){
        // if not the first item, save the end position of the previous run element
        runs[runs.length-1].end = index
      }
      runs.push({
        index,
        link:r.format.link?r.format.link.uri:undefined,
        end: text.length  // will be overwritten if not the last item
      })
    }
    const links = runs.filter(run=>run.link).map(run=>({link:run.link, text:text.slice(run.index, run.end)}))
    rows = links.map(link=>[link.text, link.link])
    //rows = links.map(link=>[[link.text], [link.link]])
  } else{
    rows =  ["no links found"]
  }

  // set the destinination
  ss.getSheetByName("Sheet1").getRange(8,1,rows.length, rows[0].length).setValues(rows)
}