0

In my server application (on Parse Cloud Code), I want save some string data. There are HTML entities here, which I want to encode.

So i find a solution with Javascript:

var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;

This code work perfectly on html pages, where document exists. But there isn't such variable on server.

How can i declare document variable? Or maybe you know another solutions for encoding HTML entities.

Eugene Trapeznikov
  • 3,220
  • 6
  • 47
  • 74
  • possible duplicate of [Which characters need to be escaped on HTML?](http://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html) – Jeremy J Starcher Mar 15 '14 at 07:33
  • Look at this discussion: http://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html. There are only a handful of characters that normally need to be escaped and those can be handled with a few `.replace()` calls. – Jeremy J Starcher Mar 15 '14 at 07:34

3 Answers3

1

You could use html-entities on Node, install it like:

npm install html-entities

then you got entities.encode(..) and entities.decode(..) functions:

var Entities = require('html-entities').XmlEntities;
entities = new Entities();
console.log(entities.encode('<>"\'&©®')); // &lt;&gt;&quot;&apos;&amp;©®

there are more examples in usage part on gihub repo.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
1

function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}

test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');

/*************
* \x26 is &ampersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>
Dave Brown
  • 923
  • 9
  • 6
0

Since I asked this question, I learned JavaScript and AJAX. So, my suggestion will be using AJAX and JSON for communication between browser and server-side.

Eugene Trapeznikov
  • 3,220
  • 6
  • 47
  • 74