Error in JavaScript action to filter characters. What the heck?

I am working on a JavaScript Draft action which, among other things, needs to remove invalid filename characters from the Draft title. I can’t reason out why it’s encountering undefined objects without issuing any errors.

I start with a draft as follows:

	Title/ with/invalid:filename char/acters\
	This is a test entry
	Throw it away.
	Really!
	Wow!

I run a processing action on this draft which only executes the following JavaScript code:

// See online documentation for examples
// https://docs.getdrafts.com/docs/actions/scripting

	var noteTitle = new String(draft.DisplayTitle);
	draft.insert((noteTitle+'\n'), 4);
	noteTitle = noteTitle.split("/").join("?"); // Replace '/' with '?'
	draft.insert((noteTitle+'\n'), 4);
	noteTitle = noteTitle.split(":").join("?"); // Replace ':' with '?'
	draft.insert((noteTitle+'\n'), 4);
	noteTitle = noteTitle.split("\x5c").join("?"); // Replace backslash with '?'
	draft.insert((noteTitle+'\n'), 4);

What I get afterwards in the draft is:

	Title/ with/invalid:filename char/acters\
	This is a test entry
	Throw it away.
	Really!
	undefined

	undefined

	undefined

	undefined

	Wow!

What am I missing? I expect the inserted lines to all be a variant of the title (first line) and I’m not understanding what I get at all. The code works in another environment (CodeRunner).

I‘ll send some more suggestions for making this easier tomorrow, but JavaScript is case-sensitive. draft.DisplayTitle is not a thing. Try draft.displayTitle

A couple of other comments:

  • If all you need is a file-name-safe version of the title, there is a template tag for that, [[safe_title]] (docs). It can be used directly in action steps that have templates for a file name, or you can get the result in a script using let fileName = draft.processTemplate("[[safe_title]]")
  • If you run into an unexpected result in a script, your quickest ways to troubleshoot are to trace back where the value goes wrong, I suggest in your example you might start by outputting the value of the noteTitle variable after each change, ways to do that:
    • alert(noteTitle) : throws up an alert displaying the value
    • console.log(noteTitle) : write the value to the action log entry for the action to view after execution.

Hope this helps!

2 Likes

Oh crud! My bad. Looked at that a thousand times, too. Thank you very much!

(Much more accustomed to languages where I’d get an “undefined variable” error at compile time.)

I didn’t know console.log would work within the Drafts environment. Splendid!