DEV Community

Morten Olsrud
Morten Olsrud

Posted on

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

Top comments (0)