Action

Convert URLs to md Links

Posted by Jihad, Last update 1 day ago

Convert all Plain URLs in the note to Markdown links with the website actual page title. Including Youtube links.

Steps

  • script

    function extractUrls(text) {
      // Match anything that looks like a URL up to the first whitespace
      let urlRegex = /(?<!\()https?:\/\/\S+/g;
      return text.match(urlRegex);
    }
    
    function extractTitleFromHtml(html) {
      let match = html.match(/<title>(.*?)<\/title>/i);
      return match ? match[1].trim().replace(/\s+/g, ' ') : null;
    }
    
    function extractYouTubeTitleFromJson(html) {
      let match = html.match(/"title":"([^"]+?)","lengthSeconds":/);
      return match ? match[1] : null;
    }
    
    function processUrls(urls, originalText) {
      let http = HTTP.create();
      let updatedText = originalText;
    
      for (let url of urls) {
        let title = null;
    
        if (url.includes("youtu.be") || url.includes("youtube.com")) {
          let resp = http.request({ url: url, method: "GET" });
          if (resp.success) {
            title = extractYouTubeTitleFromJson(resp.responseText);
          }
        }
    
        // Fallback to normal <title> tag
        if (!title) {
          let resp = http.request({ url: url, method: "GET" });
          if (resp.success) {
            title = extractTitleFromHtml(resp.responseText);
          }
        }
    
        if (!title) title = "Link";
        updatedText = updatedText.replace(url, `[${title}](${url})`);
      }
    
      return updatedText;
    }
    
    function main() {
      let urls = extractUrls(draft.content);
      if (!urls) {
        alert("No Plain URLs found.");
        context.cancel();
        return;
      }
    
      draft.content = processUrls(urls, draft.content);
      draft.update();
    }
    
    main();

Options

  • After Success Nothing
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.