How to Escape HTML Characters

If you want to display HTML code syntax, without your browser interpreting it as real markup (and render it) you need to escape reserved HTML characters first.

Look at the <h1> tag inside the <code></code> element below:

<p>You should only use one <code><h1></code> element per article.</p>

If you add the code above to an HTML document, the <h1> be interpreted as real mark up, which you obviously don’t want.

You need to escape the angle brackets < and > that surround h1 because they are reserved HTML characters.

Fortunately, it’s easy:

  • Replace < with &lt;
  • Replace > with &gt;

Example:

<p>You should only use one <code>&lt;h1&gt;</code> element per article.</p>

Now the code above will render correctly:

You should only use one <h1> element per article.

Now let’s escape some HTML code with a class attribute, e.g.: <p class="lead-paragraph"></p>.

  • Replace < with &lt;
  • Replace > with &gt;
  • Replace " with &quot;

Escaped HTML:

&lt;p class=&quot;lead-paragraph&quot;&gt;&lt;/p&gt;

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on