Finds all markdown links and makes a menu to open a url

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);
1 Like

Thanks for sharing.

Here is a similar action that uses text.matchAll(re):

https://actions.getdrafts.com/a/15m

Basically doing the same as your sample, but coded in a different way.
I’m also just learning JS :nerd_face:

Hope that’s helpful.

1 Like

Yeah I saw that in the other thread! Looks great! I was looking in the JavaScript documentation at matchAll, but I couldn’t figure out how to use it. Your action definitely makes it more clear though.

Kudos to @FlohGro for showing me how to use the (...) spread syntax, totaly new to me.

It converts the matchAll() iterable object to an (multi dim) array when used inside [ ] as in the code line below:

var matches = [...content.matchAll(regex)]

I had a hard time extracting some match elements, but as multi dim array it was much esier to do. I’m sure I missed something to get all data from matchAll(), but I’m just a novice.

Yeah I think over this summer (since there probably won’t be summer jobs for me) I might try to work on my JavaScript. Maybe come up with a few little projects to work on my skills.