Google-sheets – How to generate a basic HTML (

and
) version of another cell in Google Sheets

google sheetshtml

I'm using Google Sheets to help prepare posts for various social media sites. For some of the sites, I need to cut-and-paste HTML because my posts contain YouTube videos, and the only way to avoid using the site's UI is to post HTML directly.

So, in my sheet, I have a column main text with content such as this:

Paragraph 1

(empty line)

Paragraph 2

(empty line)

Paragraph 3

Now I want to make another column (basic html) that references main text:

<p>Paragraph 1</p>
<br>
<p>Paragraph 2</p>
<br>
<p>Paragraph 3</p>

Here is how my data is formatted:

  • There is always at least one paragraph. There may be as many as five paragraphs.
  • There is always an empty line between paragraphs.

So this is what I want to do:

  • If a line contains text, add a <p> tag in front and a </p> tag in back.
  • If there is an empty line, convert it into a <br> tag.

I have read through the list of Google Sheets functions and I have some basic familiarity with the Script Editor, but I don't know what direction to take to try to implement this.

Best Answer

It's not a pretty formula, but I got this to work (replace A1 with cell that has the source text to perform the modifications on):

=SUBSTITUTE(CONCATENATE("<p>", SUBSTITUTE(SUBSTITUTE(A1, "

", "
<br>
"), "
", "</p>
<p>"), "</p>"), "<p><br></p>", "<br>")

example of substitution done by formula

Note that the line breaks in the formula are important. This also assumes that the first line of the cell is not an empty line.