Rich Text with RegEx

I am using a slightly modified version of this action Copy as Rich Text | Drafts Directory

I need specific text to be copied as RTF rather than entire content. RegEx works fine but the end result is “undefined” When I paste text into Pages, it pastes the word “undefined”

What am I doing wrong in this script?

var report = draft.content.match(/### Procedural Information[^<>]*/);

// Process Markdown to HTML
var mmd = MultiMarkdown.create();
var html = mmd.render(report);

// Wrap raw MMD output with HTML template with styles to set base fonts.

var template = `<html>
<body>
  [[content]]
</body>
</html>
`;

var html = template.replace("[[content]]", html);

// Place in clipboard as rich-text
if (!app.htmlToClipboard(html)) {
	context.fail("Error rendering rich text from HTML.");
}

What does the text of your source draft look like? My initial guess is your regex is not matching anything, so the value in the report variable is null (aka undefined in JS).

If you put alert(report) right after that first line, what do you get?

That is what is strange. It matches and shows a popup with the exact text.

var report = draft.content.match(/### Procedural Information[^<>]*/);

alert(report);

// Process Markdown to HTML
var mmd = MultiMarkdown.create();
var html = mmd.render(report);



// Wrap raw MMD output with HTML template with styles to set base fonts.

var template = `<html>
<body>
  [[content]]
</body>
</html>
`;

var html = template.replace("[[content]]", html);

// Place in clipboard as rich-text
if (!app.htmlToClipboard(html)) {
	context.fail("Error rendering rich text from HTML.");
}

It seems to be working here with sample texts I through at it…if you alert your html var content after the MMD render, and after the template replacement, what do you get?

alert(mmd) = [object ActionKit.ScriptObjectMultiMarkdown]

var html = mmd.render(report);
alert(html) = undefined

However, if I do

var html = mmd.render(draft.content);
alert(html) = gives HTML preview

I figured it out. Kind of. This works:

var report = draft.content.match(/### Procedural Information[^<>]*/);

var report = report.toString();

A match does no produce a string and needs to be converted to one. After consulting with the wise ChatGPT, it explained that RegEx results produce an array and not a string.