Putting Tags into body

Hey all,

I’d like an action that takes tags and turns them into #tags which are then appended to the body of the text. E.g. if the tags in drafts are “snacks” and “skittles” then the text file will look like:

Note about tasty treats […]

#snacks #skittles


Basically I’m exporting drafts to obsidian, and I’d like the tags in drafts to work within the obsidian tags framework.

I’m sure this would be a simple task if I knew how to script but I don’t code. Maybe there is already an action to do this, but I wasn’t able to find one. Anyhow, any help would be greatly appreciated.

Thanks!

You can do this with a single line script step.

This JavaScript code takes each tag in the tags of a draft, and prefixes them with an octothorps then joins then together with spaces between.

draft.tags.map(tag => "#" + tag).join(" ");

To insert at the current cursor position, you could expand the line to set the current text selection in the editor to this string of hash tags.

editor.setSelectedText(draft.tags.map(tag => "#" + tag).join(" "));

Bonus: I also added a line to position the cursor at the end afterwards rather than retaining the selection of the inserted text.

Note if you have no selected text, you actually do. It just has zero length and so rather than replacing some text it is effectively just being inserted.

To always append the string of hash tags to the end of the draft, you can simply switch out the first part about the editor for an append to the end of the draft. This will add a newline automatically. Even though it occurs implicitly for a simple script, we force an update of the draft as good practice. The editor will then automatically pick up the update and display it.

draft.append(draft.tags.map(tag => "#" + tag).join(" "));
draft.update();

Welcome to day one of learning to code in Drafts :nerd_face:. In all seriousness the forum is full of suggestions for learning how to do this stuff, and everyone starts from zero.

I would note that the best way to do this would be to use @sylumer script snippet above to create a template tag, and use that template tag in your action that exports to your Obsidian vault, rather than actually adding the tags to the text of the draft. So a script step like:

draft.setTemplateTag("hashtags", draft.tags.map(tag => "#" + tag).join(" "));

Then you have a [[hashtags]] template tag you can insert in your export step (File, Dropbox, whatever you are using) and have the tags added to the exported file without changing the initial draft.

That seems cleaner to me and would not require any action if you altered the tags and re-exported, or similar.

2 Likes