Remove all newlines from HTML for JSON feed?

Given the following example Markdown as .Content:

This is a sentence.
Here is another sentence.
And here is a third.

… and the following:

{{- $contentSafe := .Content | safeJS -}}
{{- $emailReplyHTML := printf "%s%s%s" `<p><a href="mailto:me@example.com?subject=Re: “` .Title `”">Reply via email</a></p>` -}}
{{- $emailReplyHTML := $emailReplyHTML | safeJS -}}
{{- $contentHTML := printf "%s%s" $contentSafe $emailReplyHTML -}}
{{- $contentHTML := chomp $contentHTML -}}

…I would expect that $contentHTML would finally be:

<p>This is a sentence.</p>\n<p>Here is another sentence.</p>\n<p>And here is a third.</p>

…but, instead, I am getting:

<p>This is a sentence.</p>
<p>Here is another sentence.</p>
<p>And here is a third.</p>

(By the way, I tried chomp after not getting the desired result with the more conventional trim $contentHTML "\n". Also, in case you’re wondering, the intent of this is to make a working template for a JSON feed, so I need to kill the unwanted newlines for the JSON’s sake. I also tried jsonify but that produces escaping which not even htmlUnescape could fix.)

Reading responses to previous, similar questions on both this forum and Stack Overflow et al. didn’t help me figure out what I’m doing incorrectly, so I will very much appreciate any help I might receive.

Bump, bump. :slightly_smiling_face: Any takers?

First, three consecutive lines of markdown is one paragraph, not three. If you want three paragraphs, separate the lines with a empty line:

This is a sentence.

Here is another sentence.

And here is a third.

Second, the chomp function removes newline characters from the end of a string. It does not remove newline characters from the middle of a string.

Third, the trim function removes the specified characters from the beginning and end of a string. It does not remove the specified characters from the middle of a string.

Fourth, to remove characters (including new lines) from the middle of a string, use the replace function.

Fifth, removing newline characters from the middle of a block of HTML may have an undesirable effect on whitespace.

Finally, newlines are allowed within JSON strings.

2 Likes

Thanks for the explanation. Not sure why I typed the Markdown sample that way. Surely know better.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.