Javascript在服务器上编码HTML实体

Javascript encode HTML entities on server

本文关键字:HTML 实体 编码 服务器 Javascript      更新时间:2023-09-26

在我的服务器应用程序(在Parse Cloud Code),我想保存一些字符串数据。这里有HTML实体,我想对它们进行编码。

所以我找到了一个解决方案与Javascript:

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

这段代码在存在document的html页面上完美地工作。但是服务器上没有这样的变量

如何声明文档变量?或者你知道另一种编码HTML实体的解决方案。

你可以在Node上使用html-entities,像这样安装:

npm install html-entities

则得到entities.encode(..)entities.decode(..)函数:

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

在gihub repo的用法部分有更多的例子

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>

因为我问了这个问题,我学习了JavaScript和AJAX。因此,我的建议是使用AJAX和JSON在浏览器和服务器端之间进行通信。