Dear guys,
I used as I had to, but I would like to display only HTML code as it is (without its effects), as in tutorials.
Lorem ipsum... Sed ut perspiciatis...Hello World!
What can I do?
Marta
Dear guys,
I used as I had to, but I would like to display only HTML code as it is (without its effects), as in tutorials.
Lorem ipsum... Sed ut perspiciatis...Hello World!
What can I do?
Marta
If you want to display HTML code as it is, consider using <pre> and <code>
tags.
Hi “shimphillip”,
Thank you for helping me, but it also did not work.
Any idea?
Marta
You need to escape the html and put it inside pre
and code
tags.
A function to do so in JavaScript is as follows — you can use the entity map as a reference if you want to do it manually.
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
const escapeHTML = html => html.replace(/[&<>"'\/]/g, char => entityMap[char]);
Example:
<pre>
<code><h1>Hello World</h1></code>
</pre>
Should display like this:
<h1>Hello World</h1>
Hi “lionel-rowe”
Thank you for your help, I understand now.
I do NOT really WANT to do it manually, () but I am not able to use well JavaScript yet.
Marta
For a rough-and-ready solution, you can try escaping everything inside code
tags as soon as the page content is loaded, like this (JavaScript):
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('code').forEach(el => {
el.textContent = el.innerHTML;
});
});
If you do this, you’ll need to make sure not to manually escape any of the content yourself, otherwise it will be double escaped and will appear as literal HTML entities (&
and so on).
Often, this wouldn’t be a suitable solution, because allowing unescaped HTML on the page even while the page is loading is a security risk if the content came from user input. However, in your case, you know you can trust the content as you wrote it yourself.