Scripting help with file name modification

I would like to do the following:

  1. Take my draft and create a new file in Dropbox.
  2. The file name should be ‘yyyy_mm_dd_first_line_of_draft_downcased_and_underscores_replace_spaces.md ’

So far I have this URL action:
(Dropbox Action)
File: [[date|%Y_%m_%d]]_[[title]].md
Path: /folder/
Template: # [[draft]]

But the title is still mixed case and has spaces. Do I need a script to do the file name manipulation? I’m terrible with JavaScript so any tips would be helpful.

Thanks in advance!

Scripting is the way to go here, but you can still keep the majority of your existing action too.

Add a script action step at the start of your action containing the following line.

draft.setTemplateTag("filename", draft.processTemplate("[[safe_title]]").replace(/ /g,"_").toLowerCase());

This line creates a new custom tag called filename. filename is set to contain the ‘safe title’ of the draft with spaces replaced throughout (the spurious g you might spot above indicates a global replace) with underscores, and the whole thing converted to lower case.

Note I’ve not used ‘title’ but rather ‘safe title’. If the draft title contains characters that have special meaning in a file path (e.g. slashes), these can break the saving. The safe_title tag is a built-in Drafts tag that strips out invalid characters.

Once we have a custom tag we can use that in the Dropbox step like so; replacing your use of the title tag (but note you would have been better off leaving in the Dropbox default safe_title tag for the reasons described above).

Overall your steps should then look like this.

Hope that helps.

1 Like

Wow! This is perfect and works really well, thanks! I was struggling to figure out how to create custom template tags and this is super helpful!