DEV Community

Morten Olsrud
Morten Olsrud

Posted on

1

The simplest way to mimic HTMLEncode in your browser

I was working on a simple textarea based input field with a preview-feature the other day and got to a point where I wanted to render the HTML written in the textarea as written, not parsed as HTML. I was mildly surprised to see that JavaScript did not have it included by default, unlike PHP and most other server-side languages.

Looking into the issue I discovered a trove of plugins and modules for solving the matter, but that felt a bit heavy handed for my use case. I wanted something simple, fast and really small.

Doing some more research and playing around, I discovered someone who used built-in features of the browser to sole the problem, in a most ingenious way using jQuery. That library was totally unneeded for the job though, and I present to you the "vanilla" version.

Behold:

function htmlEncode(input) {
  var el = document.createElement("div");
  el.innerText = input;
  return el.innerHTML;
}

And the inverse:

function htmlDecode(input) {
  var el = document.createElement("div");
  el.innerHTML = input;
  return el.innerText;
}

Be aware though that this encodes everything HTML-related, so if you are using this on a Markdown-source, you will break your block-quotes.

Thank you for your attention!

-Morten

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay