How to display HTML tags as plain text
Table of Contents
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<h1>This is a heading.</h1>
<ul>
<li>This is a list item.</li>
</ul>
<ol>
<li>This is a list item.</li>
</ol>
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:
<
:<
>
:>
&
:&
"
:"
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>
<h1>This is a heading.</h1>
<ul>
<li>This is a list item.</li>
</ul>
<ol>
<li>This is a list item.</li>
</ol>
</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!
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with React
- Getting Started with Moon.js