【问题标题】:Extract HyperLink to URL and Text from a string of text and hyperlink从文本和超链接字符串中提取 URL 和文本的超链接
【发布时间】:2021-09-01 08:44:11
【问题描述】:

我尝试搜索,但找不到与我完全相同的人。 大多数仅适用于仅包含超链接的单元格。

我正在尝试使用来自 Google Doc 的大量超链接和文本字符串来编辑文章。我发现无法仅在 Google Doc 中提取超链接和文本,因此我将其粘贴到 Google 表格中。

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

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

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

【问题讨论】:

    标签: google-apps-script google-sheets google-docs


    【解决方案1】:

    使用下面的函数。要运行它,您必须添加 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)
    }
    

    【讨论】:

    • 您好,非常感谢您的帮助!显然,我似乎无法使用它。不确定我是否做错了什么。图像在我所做的事情上如下所示。 imgur.com/a/S6nKLb5 错误是:GoogleJsonResponseException:对 sheet.spreadsheets.get 的 API 调用失败并出现错误:请求缺少有效的 API 密钥。 (第 5 行)。
    • 您必须将脚本用作宏,即从菜单项或按钮运行它。如果您想将其用作自定义函数,则更复杂,因为您必须注意为 API 调用提供 oauth api 密钥
    • 谢谢!明白了,明白了!天哪,救命恩人!
    猜你喜欢
    • 2016-08-26
    • 2022-10-17
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2012-02-04
    相关资源
    最近更新 更多