So I got a bit of inspiration after my regex to find links today and wanted to make a script that found all markdown links in a document and presented them to be opened in Safari.
I’m not very good at JavaScript, and I found the code that helped me figure out how to get the name and the link from here. I might be interested in trying to make this into something that can select multiple links and open them all, as well as choosing if I want to keep the link or deleting the line that it’s on (because I store a lot of links as lists).
Thought this might be an interesting action for people, even though it is a bit obsolete due to link mode, but it was a fun challenge for me!
// Get markdown links and open in Safari
let d = draft.content
// Regex to identify markdown links, extracts text and link
let findRegex = /\[([^\[]+)\](\(.*\))/gm
let singleMatch = /\[([^\[]+)\]\((.*)\)/
// Variable to be used later on. names is used to make an array of text in brackets, urls makes an array for urls in parentheses, url is to set for opening in safari.
var names = [];
var urls = [];
var url = "";
const matches = d.match(findRegex)
let p = Prompt.create();
p.title = "Choose a link to open";
// gets all matches, adds text for buttons and adds matches to designated arrays
for (var i = 0; i < matches.length; i++) {
let text = singleMatch.exec(matches[i])
p.addButton(`${text[1]}`)
names.push(`${text[1]}`)
urls.push(`${text[2]}`)
}
let didSelect = p.show();
// sets name as pressed button so that it can be matched in array
let name = p.buttonPressed;
// matches name to names array, gets array index, and uses that index to find the link that it joins to, then setts it as the URL to open.
if (didSelect = true) {
let index = names.indexOf(name)
url = urls[index];
}
app.openURL(url);