Action
Format URLs
UPDATES
over 1 year ago
Sanitizes the first line.
Formats all URLs in a note to use Markdown Syntax.
Based on code from another Drafts Action.
Steps
-
script
const urlRe = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g; const titleRe = /<title>(.*?)<\/title>/i; // fetch the full text from the editor let fullText = editor.getText(); let lines = fullText.split("\n"); let firstLine = lines.shift(); let newText = ""; // create a HTTP object let http = HTTP.create(); let firstLineMatches = firstLine.match(urlRe); if (firstLineMatches) { // only get title of first URL in first line let response = http.request({ "url": firstLineMatches[0], "method": "GET" }); if (response.success) { let titleMatch = response.responseText.match(titleRe); if (titleMatch) { let title = titleMatch[1].replace(/[<>:"/\\|?*]+/g, ''); // sanitize title newText += title + "\n"; // add sanitized title as first line firstLine = firstLine.replace(firstLineMatches[0], `[${title}](${firstLineMatches[0]})`); // replace URL with markdown in first line } else { context.fail("Failed to find title in response"); } } else { context.fail("HTTP request failed"); } } newText += firstLine + "\n"; // add first line to new text // process the rest of the lines for(let line of lines) { let matches = line.match(urlRe); if (matches) { for(let url of matches) { // make HTTP get request to fetch page let response = http.request({ "url": url, "method": "GET" }); if (response.success) { let titleMatch = response.responseText.match(titleRe); if (titleMatch) { line = line.replace(url, `[${titleMatch[1]}](${url})`); } else { context.fail("Failed to find title in response"); } } else { context.fail("HTTP request failed"); } } } newText += line + "\n"; // add processed line to new text } // replace the text in the editor with the new text editor.setText(newText);
Options
-
After Success Nothing , Tags: urls Notification Info Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.