Filter out lines starting with " "

Hi, I’m writing my first Javascript action for Drafts.

Here’s my problem that I’m trying to solve. I want to copy the contents of a draft without copying the title. So I’d like to write an action that:

  1. Remove any line that starts with "# "
  2. Copy the remaining text to clipboard.

Here’s the code that I pieced together so far.

/* create an array to collect all the lines that I want to remove */
var removeTheseLines = [];
let lines = draft.content.split("\n"); // split current draft text into an array of lines.

for (let line of lines) {
  if (line.startsWith("# ", "## ", "### ", "#### ", "##### ")) {

setClipboard(contents: /* string contents*/);

Can anybody help?

Based on the split and starts with approach you have selected, something like this should work:

function dropLinesStarting(p_strInput, p_astrStarting)
	let astrKeepLines = [];

	for (let strLine of p_strInput.split("\n"))
		let bKeep = true;
			if (strLine.startsWith(strMatch)) bKeep = false;

		if (bKeep) astrKeepLines.push(strLine);

	return astrKeepLines.join("\n");

app.setClipboard(dropLinesStarting(draft.content, ["# ", "## ", "### ", "#### ", "##### "]));

The main differences are probably.

  1. I’ve restructured it a little to provide what is hopefully a more reusable function approach where you can pass in any content and any array of matches for any string.
  2. Rather than capturing the lines to remove, it captures and returns the lines to keep.

A couple of other things you may find useful.

  1. Look at the options and efficiencies using regular expressions might give you. For most drafts, this wouldn’t make a practical difference as the performance is so good, but regular expressions often give an efficient approach.
  2. The ThoughtAsylum action group has an action called TAD-Remove Lines Starting. The action group is largely built on a library of JavaScript code, which once you have the group, is very easy to incorporate into your own scripts and actions just by using the Include Action action step, and including the action called TAD. This particular action is based on the TA_removeLinesStarting() function - read the documentation for this function here.

Hope that helps.

1 Like

Would the Clipboard action with [[body]] rather than [[draft]] do the trick? More sophisticated approaches using scripts can provide more flexibility but I tend to opt for the easiest solution to the task in hand.

1 Like

If you look at the initial code and numbered requirements, you’ll see that the OP isn’t wanting to strip the title/first line of the draft, but rather a set of Markdown headings; they have referred to as titles.

1 Like