Action w/RegEx to find links and add a tag

Hi everyone! I’m trying to make a script that will find if a draft has a link in it and will add the tag “links” to it. Of course, I can do this manually, but where’s the fun in that, especially if I want to be consistent about tagging?

Right now, I don’t really know RegEx at all, and can barely write JavaScript. I’ve been looking around in the Drafts script reference and action directory but I haven’t been able to find things similar.

Currently, my script looks like this

// add links tag
// define regex to use...
const findRegex = /(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()\s])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g;

if (draft.content.(findRegex) = true) {
draft.addTag("links");
}

This RegEx is something that I found on regexr.com, and it finds markdown links, which isn’t totally ideal, but it’s a start. It doesn’t seem to me like there is a way to search a draft to get a boolean back, but I am really over my head here and any pointers or anything would be great!

In the simple case, depending on how accurate you need your link recognition to be, you could do it without regex, like…

let hasLink = draft.content.includes("http:") || draft.content.includes("https:");
if (hasLink) {
   draft.addTag("links");
   draft.update();
}

This just looks for any http: or https: occurrences.

The syntax for a regex match test would be…

let findRegex = /[http|https]:/; // you could use more advanced regex
if (findRegex.test(draft.content)) {
   draft.addTag("links");
   draft.update();
}
1 Like

Ok awesome! I’m assuming the test is just a part of regular JavaScript? This works great though, and makes more sense to me now. I’m slowly trying to build up my JavaScript knowledge by making actions, but as you can see it’s a slow process!