How to display HTML tags as plain text

Updated onbyAlan Morel
How to display HTML tags as plain text

In this post, we'll learn how to display HTML tags as plain text.

Normally, HTML tags are not visible to the end-user because they are used to render the content of the page.

However, you can still display the tags on the page anyway if you make sure of HTML entities.

HTML Entities

HTML entities are a way to display certain characters in HTML. In our case, we need a way to display the < and > characters, because these are reserved characters in HTML.

Because they have special meaning in HTML, they are not usually displayed as plain text.

Here's an example of using HTML entities to display HTML tags:

HTML
&lt;h1&gt;This is a heading.&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;This is a list item.&lt;/li&gt; &lt;/ul&gt; &lt;ol&gt; &lt;li&gt;This is a list item.&lt;/li&gt; &lt;/ol&gt;

This is how it will look like rendered in the browser:

HTML
<h1>This is a heading.</h1> <ul> <li>This is a list item.</li> </ul> <ol> <li>This is a list item.</li> </ol>

Here is a list of all the reserved HTML characters and their entities:

  • <: &lt;
  • >: &gt;
  • &: &amp;
  • ": &quot;

To encode your HTML, you can use a search and replace for every reserved character to convert it to its corresponding entity.

Preserve Formatting and Indentation

Once you encode your HTML, you will want to preserve the formatting and indentation of the HTML.

To do this, use the <pre> tag. This tag is used on on preformatted text, hence the name.

Here's an example of how to use the <pre> tag with encoded HTML:

HTML
<pre> &lt;h1&gt;This is a heading.&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;This is a list item.&lt;/li&gt; &lt;/ul&gt; &lt;ol&gt; &lt;li&gt;This is a list item.&lt;/li&gt; &lt;/ol&gt; </pre>

Conclusion

We've seen how to display HTML tags as plain text using HTML entities. We've also seen how to use the pre tag to preserve the formatting and indentation of HTML.

Hopefully, you've found this post helpful!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.